简体   繁体   中英

.addClass to only the bullet being clicked on in unordered list

I have a short unordered list with two bullets.

I added some Javascript, so that when I bullet is clicked on, it adds a class to it.

The problem is, it adds the class to all existing li's, not just the one I clicked on.

Here is the JSFiddle: http://jsfiddle.net/4sa8T/

Javascript:

$("#items li a").click(function(){

$("#items li").addClass("newClass");

});

html:

<div id="content">
    <ul id="items">
    <li><a href="#">Hello</a></li>
    <li><a href="#">Bye</a></li>    
    </ul>
</div>
$("#items li a").click(function(){
    $("#items li").addClass("newClass");
});

should be

$("#items li a").click(function(){
    $(this).parent().addClass("newClass");
});

$(this).parent() would refer to the specific li element, and $('#items li') refers to all li s under #items

The best solution for you is using:

$(this).toggleClass('newClass');

dollar this indicates using the specific clicked element...

toggleClass is an easy way to remove the added class by clicking the element again.

here is a demo jsfiddle

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