Refactoring for each statement
Hi I have written a function that is used to change text in a table cell, the table displays members of a team but is not in a readable format, so i have to convert the string output into a read开发者_运维技巧able format.
This all works fine however I was wondering if anyone could help me re-factor this function as it seems abit crude ?
Jquery Code:
$(".membersName").each(function() {
var memberName = $(this).text();
var splitmemberName = memberName.split("=");
var finalNameSplit = splitmemberName[1].split(",");
$(this).empty();
$(this).append(finalNameSplit[0]);
});
Any help or tips would be greatly appreciated. Cheers in advance
Looks fine to me! You could use RegExp
instead, but I can't say that would be better. Although this:
$(this).empty();
$(this).append(finalNameSplit[0]);
Could be shortened up to this:
$(this).empty().append(finalNameSplit[0]);
Try this: http://jsfiddle.net/C9fMN/
$(".membersName").each(function() {
$(this).text(function(i,txt) {
return txt.split("=")[1].split(",")[0];
});
});
No need to use .empty()
this way, since you're replacing the text altogether.
In fact, this way, you really don't even need the call to .each()
:
http://jsfiddle.net/C9fMN/1/
$('.membersName').text(function(i,txt) {
return txt.split("=")[1].split(",")[0];
});
just one:
$(".membersName").html(function(i, old) {
var eqpos = old.indexOf("=");
return old.substring(eqpos+1, old.indexOf(",", eqpos));
});
Chaining can help you a bit in places, for example:
$(this).empty();
$(this).append(finalNameSplit[0]);
Can become
$(this).empty().append(finalNameSplit[0]);
Also, try caching $(this)
for increased performance, i.e.
var $this = $(this);
Technically, you could amalgamate these lines:
var memberName = $(this).text();
var splitmemberName = memberName.split("=");
var finalNameSplit = splitmemberName[1].split(",");
Like so:
var finalNameSplit = $(this).text().split("=")[1].split(",");
Which means you could write it in one line of code:
$(this).empty().append($(this).text().split("=")[1].split(",")[0]);
Although your version is much more readable.
精彩评论