I am using jQuery 1.6 and I would like to improve the following code (that is, write less do more):
if (row.hasClass('line_开发者_如何学编程odd')) {
row.removeClass('line_odd');
row.addClass('line_even');
} else {
row.removeClass('line_even');
row.addClass('line_odd');
}
How can I do that?
Replace the block with:
var hasOdd = row.hasClass('line_odd');
row.toggleClass('line_odd', !hasOdd).toggleClass('line_even', hasOdd);
I would suggest use of something like http://api.jquery.com/toggleClass/, for example:
row.toggleClass("line_odd")
.toggleClass("line_even");
This assumes that no row element would have both the line_odd
and line_even
classes set initially, in order for it to have the same effect as your code.
Assuming row starts with exactly one of the two classes:
row.toggleClass("line_odd line_even")
should do the trick.
Try the following
var isOdd = row.hasClass('line_odd');
row.toggleClass('line_odd', !isOdd);
row.toggleClass('line_even', isOdd);
you can use chaining
if (row.hasClass('line_odd')) {
row.removeClass('line_odd').addClass('line_even');
} else {
row.removeClass('line_even').addClass('line_odd');
}
row.toggleClass('line_odd', row.hasClass('line_odd') ).toggleClass('line_even',
row.hasClass('line_odd') );
This is the reduced version which makes use of .toggleClass alongwith the second argument that when true adds the class and if false removes the class.
精彩评论