在选择tr来覆盖父div上的第n个子类时,如何使用jquery addClass?

时间:2022-11-28 10:31:23

I am using this to select a tr when clicked on to change the color of a tr.

我用这个来选择一个tr,当你点击它来改变tr的颜色。

$("tr").click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
});

See fiddle http://jsfiddle.net/4sn38/3/

见小提琴http://jsfiddle.net/4sn38/3/

but when I use a nth-child class on the parent div to set the tr background, my addClass isn't getting added. How can I use the nth-child class in tandem with my jquery addClass function?

但是当我在父div上使用nth-child类来设置tr背景时,我的addClass没有被添加。如何与我的jquery addClass函数一起使用nth-child类?

this is what I'm trying to do

这就是我想要做的

See fiddle http://jsfiddle.net/4sn38/

见小提琴http://jsfiddle.net/4sn38/

this didn't work

这没用

$(".list tr:nth-child(1)").addClass("selected").siblings().removeClass("selected");

this changes the color, but then I can't remove it when another is clicked

这会改变颜色,但是当单击另一个时我无法删除它

$(this).css('background','blue');

Any ideas what I'm doing wrong?

我有什么想法我做错了吗?

1 个解决方案

#1


6  

The javascript seems to be working just fine, the issue is not being more specific with your CSS, as this

javascript似乎工作得很好,问题不是更具体的CSS,因为这

.list tr:nth-child(odd) {
    background: #CCC; 
}

is more specific than this:

比这更具体:

tr.selected {
    background-color: #FFCF8B;
}

so you have to change it to

所以你必须把它改成

.list tr.selected {
    background-color: #FFCF8B;
}

FIDDLE

Read more on CSS specificity!

阅读更多CSS特异性!

#1


6  

The javascript seems to be working just fine, the issue is not being more specific with your CSS, as this

javascript似乎工作得很好,问题不是更具体的CSS,因为这

.list tr:nth-child(odd) {
    background: #CCC; 
}

is more specific than this:

比这更具体:

tr.selected {
    background-color: #FFCF8B;
}

so you have to change it to

所以你必须把它改成

.list tr.selected {
    background-color: #FFCF8B;
}

FIDDLE

Read more on CSS specificity!

阅读更多CSS特异性!