简体   繁体   English

如何在复选框上使用addClass仅将div中的ID作为目标

[英]How to target only the ID in the div with addClass on a checkbox

I am trying to only target the div associated with the checkbox. 我试图只定位与复选框关联的div。 Right now the script I am using only changes the class of the first div with the ID of taskList instead of the one where the checkbox is located. 现在,我正在使用的脚本仅更改具有taskList的ID的第一个div的类,而不是复选框所在的类。

$('input:checkbox').change(function () {
    if ($(this).is(":checked")) {
        $('#taskList').addClass("complete");
    } else {
        $('#taskList').removeClass("complete");
    }
});

id should be unique each element. id每个元素都应该唯一。 Use class taskList instead like following. 使用类taskList代替,如下所示。

 $('input:checkbox').change(function () { if ($(this).is(":checked")) { $(this).closest('.taskList').addClass("complete"); } else { $(this).closest('.taskList').removeClass("complete"); } }); 
 .complete { border: 1px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="taskList"> <input type="checkbox"/> </div> <div class="taskList"> <input type="checkbox" /> </div> 

you should us closest over here. 您应该在这里最靠近

Suppose you have html like this:- 假设您有这样的html:

<div class="taskList">
    <input type="checkbox"/>
</div>
<div class="taskList">
    <input type="checkbox" />
</div

Now what colsest will do is, it goes for each element in the set, get the first element that matches the selector by testing the element itself. 现在,colestest要做的是,对集合中的每个元素进行测试,通过测试元素本身来获取与选择器匹配的第一个元素。

so on check ( change ) you should do, 如此检查(更改)您应该做的,

$(this).closest('.taskList').addClass("yourClass");

Full code goes, 完整的代码

$('input:checkbox').change(function () {
    if ($(this).is(":checked")) {
        $(this).closest('.taskList').addClass("yourClass");
    } else {
        $(this).closest('.taskList').removeClass("yourClass");
    }
});

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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