如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:37:02  来源:igfitidea点击:

How to change background-color on click with jQuery?

jqueryclickbackground-color

提问by AabinGunz

I have a demo here.

这里有一个演示。

I want to accomplish something similar to this.

我想完成与此类似的事情。

I'm not able to figure out where am I going wrong.

我无法弄清楚我哪里出错了。

回答by Erick Petrucelli

Based on your demos, you is just changing background-colorof 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....