开发者

CSS won't dynamically change with .addClass() or .css()

开发者 https://www.devze.com 2023-03-06 20:21 出处:网络
I have a table that has rows wi开发者_开发知识库th different classes depending on what color it should be.On the click of a button I want the background color of the row to change instantly.I tried bo

I have a table that has rows wi开发者_开发知识库th different classes depending on what color it should be. On the click of a button I want the background color of the row to change instantly. I tried both .addClass() and .css() but they both fail. On click, I have a function that checks whether the row is colored or not, that works fine.

Here are the pieces of code I'm using and the css classes that go along with the rows.

If a row is white:

$("#"+table+"_row_"+id).addClass("table-1").removeClass("table-0");

or

$("#"+table+"_row_"+id).css("background-color","orange");

If a row is orange:

$("#"+table+"_row_"+id).addClass("table-0").removeClass("table-1");

or

$("#"+table+"_row_"+id).css("background-color","white");

css:

table.tablesorter .table-1{
background-color:orange;
}
table.tablesorter .table-0{
background-color:white;
}


The only thing I can think of is that "#"+table+"_row_"+id won't give you the element you want. Check if that selector gives you any elements at all, and verify they are the right one.

I prefer to use classes only for this, because else you're still embedding style in code while you just got it out of your html. You can use hasClass to do this.

Speed things up by storing the reference:

var x = $('#'+table+'_row_'+id);
if (x.hasClass('table-0'))
{
  x.addClass('table-1').removeClass('table-0');
}
else
{
  x.addClass('table-0').removeClass('table-1');
}

It makes debugging and updating easier too, since you know that if x is right once, it will always be right. And you can inspect it easier too.


Have you checked the CSS cascading order, perhaps with Firebug or WebKit's Web inspector?

When updating a CSS class, you'll need to take care the cascading order. Otherwise, it may not turn out to be the effect you are after.


Check out this fiddle. It is a stripped down version of what I believe you're trying to make work. http://jsfiddle.net/edelman/ntPGb/1/

0

精彩评论

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