How do I check for a css value using jQuery?
After the user clicks on a table row, I want it to check if the table row's background-color is white, and if so, it will change the color to light blue.
The code I am using开发者_StackOverflow is not working. Here it is:
$("#tracker_table tr#master").click(function(){
if($(this).css("background-color") == "#FFFFFF") {
$(this).css("background-color", "#C2DAEF");
}
});
I think there is something wrong with my if statement. How do I check for a css value using jQuery?
Looks like it gets returned in the form rgb(x, y, z)
, so your code should be:
$("#tracker_table tr#master").click(function(){
if($(this).css("background-color") == "rgb(255, 255, 255)") {
$(this).css("background-color", "#C2DAEF");
}
});
Edit: That being said, I'd suggest you use classes instead of inspecting/setting css properties directly. Something like this:
$("#tracker_table tr#master").click(function(){
if(!$(this).hasClass("selected")) {
$(this).addClass("selected");
}
});
Css:
tr { background-color: #FFFFFF; }
tr.selected { background-color: #C2DAEF; }
While this may work, in effect you are storing information in the form of colors, and then retrieving and comparing this information later. Alconja suggests an approach that will work, but ultimately you may be better off working with classes, whose names can be defined by you to carry appropriate meaning. It's much friendlier and less brittle to have something like this:
$('#tracker_table tr#master').click( function(){
if ( $(this).hasClass('something') ) {
$(this).removeClass('something').addClass('something_else');
}
})
if you are using native javascript, you can try
document.getElementById("#SELECTOR").style.("STYLE_PROPERTY") == VALUE;
or
If you are using jQuery you can try something like
$("#SELECTOR").css("STYLE_PROPERTY") == VALUE_TO_MATCH
精彩评论