开发者

Improving to class toggling

开发者 https://www.devze.com 2023-04-02 07:59 出处:网络
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\')) {

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消