首页 > 解决方案 > 选中了所有 Checkboxes 道具,但我只希望触发一个复选框

问题描述

我有可以“添加到收藏夹”的项目列表,在这种情况下我使用复选框,因此用户可以选中复选框以添加到收藏夹,反之亦然,取消选中复选框以从收藏夹中删除。

流程假设是这样的:

  1. 当复选框未选中,并且用户单击它时,它将被选中

  2. 当复选框被选中并且用户单击它时,它将触发一个模式,要求他们确认他们是否真的想从收藏夹中删除该项目。在弹窗中,有一个确认按钮,当用户点击它时,它会取消选中复选框并关闭弹窗。

下面是html元素

    <div class="star_wrap">
      <input type="checkbox" /><label onclick="confirmLabelRemove(this)"><label>
    </div>
    i put the click event in label to trigger the input before it to be checked or unchecked

下面是为每个复选框生成唯一 ID 的代码

    var listItems = $(".star_wrap"); // the container of each checkbox
    listItems.each(function (idx) {
    $(this).find('input').attr('id', 'chkbox' + idx);
    //$(this).find('label').attr('for', 'chkbox' + idx); I don't want this 
    feature because If I click on the label it will prop check the 
    checkbox before the pop up modal show up.
});

下面是触发道具检查事件的代码

    function confirmLabelRemove(obj) {
    var thisLabelInput = $(obj).prev(); // find the input before the label

    if ($(thisLabelInput).is(':checked')) {
    overlayConfirmShow(); // transparent layer to prevent back content clickable
    $('.confirmation_box').addClass('show'); // show the pop up modal

    $('#confirmBoxConfirm').on('click', function () {
        $(obj).prev().prop('checked', false);
        $(obj).closest('.grid-item').addClass('unfav');
        overlayConfirmHide();
        $('.confirmation_box').removeClass('show');
     });
    } else {
      $(obj).closest('.grid-item').removeClass('unfav');
      $(obj).prev().prop('checked', true);
     }
    }

如果只有 1 个复选框,它工作得很好。但是当它们是复选框列表时,取消选中和选中复选框 1 将触发先前选中或未选中的复选框。请指教,谢谢。

标签: jquerycheckboxprop

解决方案


$('#confirmBoxConfirm').on('click', function () {当此行多次运行 ( ) 并且它们未被删除时,您实际上将多个处理程序附加到 click 事件。这意味着单击时,先前设置的每个处理程序都将运行。

您可以先尝试删除它:

$('#confirmBoxConfirm').off('click').on('click', function () {

或者如果您已经有其他点击处理程序并且只想删除这个,它必须是一个命名函数:

function theClick() {
    $(obj).prev().prop('checked', false);
    $(obj).closest('.grid-item').addClass('unfav');
    overlayConfirmHide();
    $('.confirmation_box').removeClass('show');
};

$('#confirmBoxConfirm').off('click', theClick).on('click', theClick);

推荐阅读