简体   繁体   中英

JQuery changing background color of unordered list item

I have an unordered list and i would like to change the background color of each item when that item is selected(items in list are link tags) here is the JQuery code that I have so far.

$("#cat").focusin(function(){
    $("#cat").css("background-color", "#1796cf");
});

$("#cat").focusout(function(){
    $(this).css("background-color", "#333333");
});

#cat is set as ID in the html for each item in my list. This works but only works on the first item in the unordered list. Please help me get this to work on every item in my list.

Id should be unique use class instead of id

$(".cat").focusin(function(){
    $(this).css("background-color", "#1796cf");
});

$(".cat").focusout(function(){
    $(this).css("background-color", "#333333");
});

Try another way

$('.cat').focus(function() {
       $(this).css("background-color", "#1796cf");
    }).blur(function() {
        $(this).css("background-color", "#333333");
 });

ok after your comment I've re-made my answer, here are the things you need in order to make it work:

HTML :

<ul class="selectable">
    <li><a href="#">text</a></li>
    <li><a href="#">text</a></li>
    <li><a href="#">text</a></li>
</ul>

CSS :

.selectable li {
    background-color: #333;
}

.selectable li.cat {
    background-color: #1796cf;
}

.selectable li a {
    color: white;
}

.selectable > li > a {
    display: block;
}

and finally some JQuery to do the magic:

$('.selectable > li > a').click( function( e ) {
    //prevent click from anchors, you can avoid this step if you need them
    e.preventDefault();
    //look for any previous class asigned
    $('.selectable').find('li').removeClass('cat');
    //add class to the li
    $(this).parent().addClass('cat');
});

link to the updated fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM