簡體   English   中英

單擊復選框並隱藏復選框時,將帶有jQuery的類添加到復選框的父元素

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

我有一個看起來像切換按鈕的列表,但實際上它們是首選項的清單。 這樣,輸入是隱藏的,並且如果選中此復選框,我想將一個類添加到父標簽。

除了不滿意的IE8之外,一切都很好。 我認為這可能是.change,但是我無法完全確定如何使用.click來實現這一點,但我的嘗試未能成功結束。

在這里!

HTML

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

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');
    }
});

那么,如果選中了,檢查它嗎?

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

沒有什么意義,為什么不只是:

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

永遠不要刪除選中的屬性,使用.prop('checked', false);將其設置為false .prop('checked', false); this.checked = false

嘗試添加$(this).parent().children('.btn-flat').addClass('grey'); 到if塊和$(this).parent().children('.btn-flat').removeClass('grey'); 到javascript的else塊,然后將.checkbox .grey{background-color: #ccc;}到css文件。 這樣,它定位到特定的html元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM