I have written a code to change the CSS (color font) of tr, but it's not working. If I remove the condition and use $(this开发者_运维百科).css("color","white");
then it works perfectly. But when I do this in if condition it fails to change the text color. What am I doing wrong with this one? Thanks.
$('tr').click(function () {
$(this).toggleClass('hilite');
//$(this).css("color","white");
if($(this).css("color") == "black"){
alert("In first if");
$(this).css("color","white");
}else{$(this).css("color","black");}
});
I suspect if you look at the return value of $(this).css("color")
(e.g., in a debugger), you'll find that it's not "black" but instead "rgb(0,0,0)" or similar. (You can see it here — I get "rgb(0, 0, 0)" in Chrome, probably many other browsers as well.) You'll need to handle that, either by keeping track of the colors (or perhaps based on your "hilite" [sic] class) or by parsing the result.
The best thing, of course, is to have your "hilite" class control the text and background color, so you don't have to do it in your JavaScript at all. E.g., with this rule:
tr.hilite, tr.hilite td, tr.hilite th {
background-color: black; /* Or whatever your dark background color is */
color: white;
}
Off-topic: Every time you call $()
, there are multiple function calls and a memory allocation involved, so if you're going to do that several times in a row, it's best to grab the result and reuse it.
$('tr').click(function () {
var $this = $(this); // Grab it once
$this.toggleClass('hilite'); // Use it throughout
//$this.css("color","white");
if($this.css("color") == "black"){ // (You'll still need to fix this)
alert("In first if");
$this.css("color","white");
}else{$this.css("color","black");}
});
Make use of classes instead of dealing with .css
calls. You can easily check if an element has a class by calling .hasClass('foo')
.
Maybe that is what the 'hilite' class is for? If so, you can change to this:
$('tr').click(function () {
if($(this).hasClass("hilite")){
alert("In first if");
}
$(this).toggleClass('hilite');
});
精彩评论