【问题标题】:jQuery click() on div fires parents click() eventdiv 上的 jQuery click() 触发父母 click() 事件
【发布时间】:2012-11-20 00:34:57
【问题描述】:
    <div class="parent">
        <div class="child">
        </div>
    </div>
    <script type="text/javascript">
    $(document).on("click", ".parent", function(event){
        doAjaxCall();
    });

    $(document).on("click", ".child", function(event){
        doSomething(); // and DON'T call doAjaxCall();
    });
</script>

event.stopPropagation();return false; 也不起作用。可能是什么问题呢?

编辑:好的,显然它正在处理 js fiddle:http://jsfiddle.net/Smbb4/ 我必须再次检查我的代码..

Edit2:解决方案:

    $('.parent').click(function(event) {

        if ( $(event.target).closest('.child').length > 0 ) {
            var close = $(event.target).closest('.child');
            var windowID = close.data('windowid');

            closeWindow(windowID);
            return false;
        }
        });

【问题讨论】:

  • 上个月我遇到了一个关于同步 AJAX 调用、preventDefault()/stopPropagation() 和 Firefox 的奇怪问题。似乎在 Firefox 下的 keydown 处理程序中使用同步 AJAX 调用时,默认行为总是被传播。更多信息在这里:stackoverflow.com/questions/13360035/…这是你的用例吗?

标签: jquery onclick


【解决方案1】:

对于父级,您只需要一个单击处理程序。以常规方式处理事件,除非原始目标在子对象中,在这种情况下,您需要分支并做一些不同的事情。

$(document).on("click", ".parent", function(event){

    if ( $(event.target).closest('.child').length > 0 ) {
        doSomething;
        return false;
    }

    doAjaxCall();
});

【讨论】:

  • @DesertP 没问题,很高兴它仍然有用!
【解决方案2】:

发现问题:

因为您在 body 元素上使用 on 而不是直接在 img.theater 事件将冒泡到 body 元素,并且 它是如何工作的。

在事件冒泡过程中 .theater-wrapper 元素点击事件 将被触发,以便您看到它。

jQuery on() stopPropagation not working?

解决方案:

$('.parentParent').on("click", ".child", function(event){});

【讨论】:

  • Since you are using on on the body element and not directly on img.theater the event is going to bubble up to body element and that is how it works. 在您的方案中并非如此。 This fiddle 按预期工作,将其中的 document 替换为 body,它仍然可以工作。您描述的事件冒泡问题曾经是使用live() not on() 时的情况。 live() 过去总是让一切都冒泡到document,因此stopPropagation() 不起作用。 on() 按预期工作。
  • 而这个:$('.parentParent').on("click", ".child", function(event){}); 与这个:$(document).on("click", ".child", function(event){} 完全相同,这就是你所拥有的。在使用on() 时,绑定到文档而不是最近的静态元素并不会突然阻止stopPropagation()return false.child 元素中工作。
【解决方案3】:

试试这个方法

$(".parent").click(function() {

});

$(".child").click(function() {

});

它应该可以正常工作。不必将它们放在 document.ready 函数中

【讨论】:

  • 在我的情况下是这样,因为我在运行时添加了这些 div。 .click().. 有效,但我不能使用它。 .on和stopPropagation()肯定有问题
  • 删除 AJAX 部分后代码是否正常工作?如果是这样,请查看我对您问题的评论
  • It is not necessary to put them in the document.ready function 如果方法在目标元素位于 DOM 之前执行,则不会绑定事件。为了防止这种风险,最好在 DOM 准备好时进行绑定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多