簡體   English   中英

如何檢查下一個復選框?

[英]How to check the very next checkbox?

我面臨的問題是我具有相同的“按鈕復選框”,但是一旦單擊其中的一個,我只希望選中和取消選中最接近的復選框。

<span class="button-checkbox">
    <button type="button" class="btn btn-sm btn-default btn-private">
        <i class="fa fa-square-o private"></i>
     <button>
     <input name="private" type="checkbox" class="hidden" />
</span>
<span class="button-checkbox">
    <button type="button" class="btn btn-sm btn-default btn-private">
        <i class="fa fa-square-o private"></i>
     <button>
     <input name="private" type="checkbox" class="hidden" />
</span>

我當前使用的JavaScript代碼是:

$(document).on("click", ".btn-private", function() {

    $(this).find("i").toggleClass('fa-square-o fa-check-square-o');
    $(this).find('input:checkbox').prop("checked", true);

})

出於某些奇怪的原因, $(this).find("i").toggleClass('fa-square-o fa-check-square-o'); 正確地切換了類,但是似乎沒有正確選擇$(this).find('input:checkbox') ,因為如果我手動分配ID和$('#ID').prop("checked", true); 它得到正確檢查。

我將如何解決此問題以及如何取消選中單擊框的任何想法,將不勝感激!

采用

$(document).on("click", ".btn-private", function() {
    $(this).find("i").toggleClass('fa-square-o fa-check-square-o');
    $(this).next().prop("checked", true); // here
})

否則,您正在尋找按鈕內部的復選框。

$(this).find('input:checkbox').prop("checked", true); 正在尋找button內的input

嘗試查看按鈕后的下一個元素:

$(this).next().find('input:checkbox').prop("checked", true);

這是一個有效的Codepen: http ://codepen.io/ZevanRosser/pen/wgjOQE

暫無
暫無

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

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