Javascript jquery:onclick 更改背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5103691/
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
jquery: onclick change background color
提问by gautamlakum
I have following UL - LI html.
我有以下 UL - LI html。
<UL>
<LI><span id='select1'>Text</span></LI>
<LI><span id='select2'>Text</span></LI>
<LI><span id='select3'>Text</span></LI>
<LI><span id='select4'>Text</span></LI>
<LI><span id='select5'>Text</span></LI>
<LI><span id='select6'>Text</span></LI>
</UL>
If I click on specific <span>, its background color should be changed. i.e. if I click on span having id='select3', its background-color should be changed.
如果我点击 specific <span>,它的背景颜色应该改变。即如果我点击 span id='select3',它的背景颜色应该改变。
How this can be done using jQuery?
如何使用 jQuery 做到这一点?
回答by Prakash
Try this one :
试试这个:
$('li span[id^="select"]').click(function(){
$(this).css('background-color',"#ccc")
})
what it does is, clicking the spaninside lihaving id starting with 'select' changes the backgound color.
它的作用是,单击以“select”开头的 idspan内部li会更改背景颜色。
回答by Alexey Ogarkov
You can use the following
您可以使用以下
jQuery("#select1").click(function(){jQuery(this).css({'background-color':'red})});
Hope it helps.
希望能帮助到你。
Update my answer to put handler on each select. You can add some attr to your span elements to represent color. e.g. <span rel="red">Text</span>.
And then you can write handler like
更新我的答案以在每个选择上放置处理程序。您可以向 span 元素添加一些 attr 来表示颜色。例如<span rel="red">Text</span>。然后你可以像这样写处理程序
jQuery("ul span[id^='select']").click(function(){jQuery(this).css({'background-color':jQuery(this).attr('rel')})});
回答by TimCodes.NET
Try
尝试
$("span").click(function(){
if($(this).attr('id') == "select3") $(this).css('background-color', 'red');
});
回答by Andrea
If you have many list elements, you may want to use event delegation and only manage a click on the ul. So you can do
如果您有许多列表元素,您可能希望使用事件委托并且只管理对ul. 所以你可以做
$('ul').click(function(event) {
switch($(event.target).attr('id')) {
case select1:
$(event.target).css('background-color', 'red');
break;
//More case statements
}
});

