【问题标题】:jQuery - Click event on div but not on checkbox in the divjQuery - div 上的单击事件,而不是 div 中的复选框
【发布时间】:2011-01-03 20:44:57
【问题描述】:

我正在尝试在 div 上设置点击事件,如果在 div 中的复选框之外的任何位置单击该 div,我希望触发该事件。如果单击复选框,我不希望触发 div 的单击事件。我在复选框上设置了一个点击事件并返回 false,这会停止 div 的点击事件,但也不允许复选框被选中。这是我现在拥有的:

$('.theDiv').click(function() {
    // Click event for the div, I'm slide toggling something
    $('.sub-div', $(this)).slideToggle();
});

$('.checkboxInTheDiv').click(function() {
    // Do stuff for the checkbox click, but dont fire event above
    return false; // returning false won't check/uncheck the box when clicked
})

【问题讨论】:

    标签: jquery checkbox click


    【解决方案1】:

    不要返回 false(这会阻止默认操作),而是尝试停止传播。

    $('.checkboxInTheDiv').click( function(e) {
        e.stopPropagation();
        ... other stuff...
        return true;
    });
    

    【讨论】:

    【解决方案2】:

    您需要查看传递给点击处理程序的event 对象并查看它是什么类型。查看Event.Type 文档了解更多信息。

    function handler(event) {
      var $target = $(event.target);
      if( $target.is("li") ) {
        $target.children().toggle();
      }
    }
    
    $("ul").click(handler).find("li > ").h
    

    注意:从链接 URL 复制的代码。

    【讨论】:

    • 这个答案特别有用,因为即使使用.live() 方法绑定事件,它也可以工作。
    【解决方案3】:

    试试简单的return;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      相关资源
      最近更新 更多