简体   繁体   English

单击复选框并隐藏复选框时,将带有jQuery的类添加到复选框的父元素

[英]Adding a class with jQuery to parent element of a checkbox when that is clicked and the checkbox is hidden

I have a list designed to look like toggle buttons, but they're actually a checklist of preferences. 我有一个看起来像切换按钮的列表,但实际上它们是首选项的清单。 As such, the input is hidden and I want to have a class added to the parent label if the checkbox is checked. 这样,输入是隐藏的,并且如果选中此复选框,我想将一个类添加到父标签。

It all works great, except for in IE8 which isn't happy. 除了不满意的IE8之外,一切都很好。 I think this may be the .change, but I can't quite work out how to achieve this with .click, my attempts have ended unsuccessfully. 我认为这可能是.change,但是我无法完全确定如何使用.click来实现这一点,但我的尝试未能成功结束。

FIDDLE HERE! 在这里!

HTML HTML

<li>
    <label class="checkbox">
        <input type="checkbox" data-toggle="checkbox" />
        <span class="btn-flat">Option</span>
    </label>
</li>

JS JS

$('.checkbox input').change(function() {
    if (this.checked) {
        $(this).parent('.checkbox').addClass('checked');
        $(this).attr('checked','checked');
    }else {
        $(this).parent('.checkbox').removeClass('checked');
        $(this).removeAttr('checked');
    }
});

So, if this is checked, check it ? 那么,如果选中了,检查它吗?

if (this.checked) {
    $(this).attr('checked','checked');
}

doesn't make much sense, why not just : 没有什么意义,为什么不只是:

$('.checkbox input').on('change', function() {
    $(this).parent('.checkbox').toggleClass('checked', this.checked);
});

and never ever remove the checked attribute, set it to false with .prop('checked', false); 永远不要删除选中的属性,使用.prop('checked', false);将其设置为false .prop('checked', false); or this.checked = false this.checked = false

try adding $(this).parent().children('.btn-flat').addClass('grey'); 尝试添加$(this).parent().children('.btn-flat').addClass('grey'); to the if block and $(this).parent().children('.btn-flat').removeClass('grey'); 到if块和$(this).parent().children('.btn-flat').removeClass('grey'); to the else block of the javascript and then add .checkbox .grey{background-color: #ccc;} to css file. 到javascript的else块,然后将.checkbox .grey{background-color: #ccc;}到css文件。 This way it targets the specific html element. 这样,它定位到特定的html元素。

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

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