开发者

jquery: onclick change background color

开发者 https://www.devze.com 2023-02-12 22:57 出处:网络
I have following UL - LI html. <UL&开发者_高级运维gt; <LI><span id=\'select1\'>Text</span></LI>

I have following UL - LI html.

<UL&开发者_高级运维gt;
<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.

How this can be done using jQuery?


Try this one :

$('li span[id^="select"]').click(function(){
   $(this).css('background-color',"#ccc")
})

what it does is, clicking the span inside li having id starting with 'select' changes the backgound color.


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

jQuery("ul span[id^='select']").click(function(){jQuery(this).css({'background-color':jQuery(this).attr('rel')})});


Try

$("span").click(function(){
  if($(this).attr('id') == "select3") $(this).css('background-color', 'red');
});


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').click(function(event) {
    switch($(event.target).attr('id')) {
        case select1:
            $(event.target).css('background-color', 'red');
            break;
        //More case statements
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号