如何使用 jQuery 在单击时更改背景颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6265139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change background-color on click with jQuery?
提问by AabinGunz
回答by Erick Petrucelli
Based on your demos, you is just changing background-color
of spans, regardless of their id
, so those ifs are very unnecessary. Just itis working well:
根据您的演示,您只是在更改background-color
跨度,而不管它们的id
,因此这些 if 是非常不必要的。只是它运行良好:
$(".AccordionPanelContent span").click(function() {
$(".AccordionPanelContent span").css("background-color", "white");
$(this).css("background-color", "red");
});
回答by Roko C. Buljan
DEMO
演示
The code used:
使用的代码:
$("span[id*='select']").click(function() {
$("span[id*='select']").removeClass('selected');
$(this).addClass('selected');
});
And a bit of CSS:
还有一点CSS:
.selected{
background:#f00;
}
You can see the $("span[id*='select']")
, it restricts the selector to only the ID elements that have a name containing the text: select....
您可以看到 $("span[id*='select']")
, 它将选择器限制为仅具有包含文本的名称的 ID 元素:select....