简体   繁体   中英

JQuery Selected Checkbox Item Background Color

I've got the code below "working" but I can't figure out how to get the click event to be just for the checkbox. Right now just click the li will toggle my background color...I'm totally missing something here. All I need is that for each li that has a checkbox checked the bg color will change and when unchecked it will return to it's previous color. Can anyone help me out.

<script type="text/javascript">

$(document).ready(function() {
    $('.list-item').find('input:checkbox').each(function(index) {
        var selectedlistitem = $('.list-item');
        $(selectedlistitem).click(function () {                     
            $(this).toggleClass('selected');
        });
    });
});
</script>


<ul> class="list-item-container">
<li class="list-item"><input type="checkbox" />Item 1</li>
<li class="list-item"><input type="checkbox" />Item 2</li>
<li class="list-item"><input type="checkbox" />Item 3</li>
</ul>

You're overcomplicating things quite a bit, you just need to do this:

$('.list-item :checkbox').click(function() {
    $(this).closest('.list-item').toggleClass('selected');
});

Demo: http://jsfiddle.net/ambiguous/ddkD9/

You don't need $().find().each() , you can flatten your $().find() into a single selector and jQuery functions are (almost always) set-based already so there's no need for iteration using each . Also, input:checkbox is redundant, all checkboxes are <input> s already so you just need :checkbox to find checkboxes.

Inside the callback you can use closest to go back up the DOM from the checkbox, this , to find the containing <li class="list-item"> .

$('.list-item input:checkbox').click(function() {
    var selectedlistitem = $(this).parent('li');
    selectedlistitem.toggleClass('selected');
});

http://jsfiddle.net/3s2pk/

You dont need to do the each function, and within each one should refer to the clicked element itself, and not do a global selector.

$('.list-item :checkbox').click(function () {
    $(this).parent().toggleClass('selected');
});

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