简体   繁体   English

如果选中了一个复选框,我如何检查 JQuery,如果选中,则将 class 添加到父 label?

[英]How can I check with JQuery if a checkbox is checked and if so add a class to the parent label?

I would like, on load of the page, to check if a checkbox is:checked Then if it is, add a class to the label.我想在加载页面时检查一个复选框是否:选中如果是,则将 class 添加到 label。 I currently have the following script but it doesn't work.我目前有以下脚本,但它不起作用。

$(document).ready(function() {
    $('input').is(':checked') {
        $(this).parent('label').toggleClass('label--active');
    });
});

My HTML is:我的 HTML 是:

<label class="container-checkbox" for="checkOne">
    <span class="checkbox-label">Option one</span>
    <input type="checkbox" id="checkOne">
    <span class="checkmark"></span>
</label>

I can not change the DOM order as these are custom checkboxes.我无法更改 DOM 顺序,因为这些是自定义复选框。

I guess you can use this:我想你可以使用这个:

 $(document).ready(function() { let checkboxone = document.getElementById('checkOne'); checkboxone.addEventListener('change',function() { checkboxone.parentNode.classList.toggle('label--active'); }); });

How does is work?工作怎么样?

Everytime when the checkbox is clicked, the class 'label--active' will be added / removed.每次单击复选框时,都会添加/删除 class 'label--active'。

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

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