【问题标题】:jQuery prevent checkbox checking nested inside another DIVjQuery防止复选框检查嵌套在另一个DIV中
【发布时间】:2012-09-27 19:02:29
【问题描述】:

我已经查看并尝试了有关此主题的许多答案,但似乎找不到有效的解决方案。我可能会遗漏一些明显的东西,在这种情况下我很抱歉,但这是我的问题:

我有一个嵌套在 DIV 元素中的复选框,这个 DIV 元素附加了一个 jQuery click 事件,然后检查复选框是否被选中,然后选中/取消选中它。根据它是否已被选中/取消选中,然后将变量发送到 PHP 脚本以添加到会话变量中。

当它是被单击的 DIV 时,这一切都很好,但是当单击复选框时,我认为会发生一些冒泡,因为它每次都会触发取消选中复选框的事件。我尝试使用附加到复选框单击事件的stopPropogation();preventDefault();,但无济于事。

这里有一些示例代码可以尝试使这一点更清楚:

复选框 HTML 代码:

<div class='bundle_offer' id='bundle_offer_0'>
    <input type="checkbox" />
</div>

点击功能:

// Click function on bundle offer div to add booster
$(".bundle_offer").click(function (event) {

    // IF its not the checkbox clicked, send over the div id
    if (event.target.type !== 'checkbox') {

        var bundle_offer_div_id = "#"+this.id;
        bundle_offer_click(bundle_offer_div_id);
    }
    // ELSE find div id and send it
    else{
        var bundle_offer_div_id = $(this).closest(".bundle_offer").attr("id");
        bundle_offer_div_id = "#"+bundle_offer_div_id;
        bundle_offer_click(bundle_offer_div_id);
    }
}); // end bundle offer click function

bundle_offer_click 函数只需获取单击的 DIV 的 id,找到复选框,选中/取消选中它,然后通过 AJAX 将适当的变量发送到 PHP 脚本。

编辑:

我设法通过稍微调整逻辑来解决问题,这是我将其更改为:

// Click function on bundle offer div to add booster
$(".bundle_offer").mouseup(function (event) {

    // Get whether checked or not
    var isChecked = $(this).find('input').is(':checked');

    // IF its not the checkbox clicked
    // check/uncheck
    // send over the div id
    if (event.target.type !== 'checkbox') {
        if(isChecked == false){
            // Check
            $(this).find('input').attr('checked',true);
        }
        else{
            // Uncheck
            $(this).find('input').attr('checked',false);
        }
        var bundle_offer_div_id = "#"+this.id;
        bundle_offer_click(bundle_offer_div_id, isChecked);
    }

    // ELSE find div id and send it
    else{   
        var bundle_offer_div_id = $(this).closest(".bundle_offer").attr("id");
        bundle_offer_div_id = "#"+bundle_offer_div_id;
        bundle_offer_click(bundle_offer_div_id, isChecked);
    }
}); // end bundle offer click function

主要区别在于使用 mouseup 函数,并在 mouseup 函数中执行检查/取消选中复选框的逻辑,而不是 bundle_offer_click 之一。

【问题讨论】:

  • 为什么你把你的复选框包装到DIV??你为什么不给你的复选框定义一个类或ID并捕捉它的事件???
  • 我把它包装到了一个DIV中,因为上面的代码被简化了,实际上DIV中还有其他东西,然后被拉到bundle_offer_click函数中传递给PHP脚本

标签: javascript jquery html checkbox click


【解决方案1】:

如果您单击复选框,浏览器会自动选中/取消选中复选框。您不需要使用 JavaScript 执行此操作。

我相信在bundle_offer_click 内部,您正在选中/取消选中复选框。你应该在bundle_offer_click 中传递一个标志作为第二个参数,标志值应该取决于点击的元素。并在bundle_offer_click 内部基于标志对复选框采取行动。

代码:

function bundle_offer_click(id, isCheckBoxClicked){
    if(isCheckBoxClicked){

       //do nothing on check box
     }
}

【讨论】:

  • 感谢类似的方法似乎解决了我的问题,我会用我的做法更新我原来的帖子
猜你喜欢
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
相关资源
最近更新 更多