stopPropagation的jquery没有按预期工作

时间:2014-04-06 06:48:10

标签: javascript jquery firefox

我目前正在使用ui录音机,我有时会使用jquery的stopPropagation吸收事件,这被定义为

    stopPropagation: function () {
        this.isPropagationStopped = K;
        var a = this.originalEvent;
        !a || (a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0)
    }

通过jquery。我吃这个活动

    absorbClick: function(e) {
        e.stopPropagation();
        e.preventDefault();
    }

并通过函数

将事件附加到所有元素
  jQuery(frame.document).bind("click", {}, function(e) {
        e.stopPropagation();
        e.preventDefault();
    }, true);

令人惊讶的是,对于某些网站,我无法吸收某些网站上的点击事件。它运作正常。

以上流程对此示例网站无效。甚至在调用absorbClick函数之前,文本就会在下一个中发生变化。为什么我无法吸收事件?

<html>
    <head>
        <title>Repro</title>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    </head>
    <body>
        <div id="mydiv">Click me!</div>
        <script>
            $('#mydiv').click(function() { $('#mydiv').html("You have clicked me!") });
        </script>
    </body>
</html>

虽然它适用于

<div class="central-featured-lang lang1" lang="en">
    <a class="link-box" href="//en.wikipedia.org/" title="English — Wikipedia — The Free Encyclopedia"><strong>English</strong><br>
        <em>The Free Encyclopedia</em><br>
        <small>4 479 000+ articles</small>
    </a>
</div>

以上所有流程均为https://github.com/sebuilder/se-builder/blob/master/seleniumbuilder/chrome/content/html/js/builder/verifyexplorer.js的一部分。我正在为sebuilder解决这个问题。

1 个答案:

答案 0 :(得分:4)

问题是示例中的事件处理程序在执行事件处理程序之前执行,因为它直接绑定到元素。

您的事件处理程序已添加到文档的根目录中,因此它将是为任何事件执行的最后一个处理程序。

如果要在触发任何其他处理程序之前捕获事件,则必须使用apture phase

绑定c addEventListener:中的处理程序
document.addEventListener('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
}, true); // <- passing true binds the handler in the capture phase

jQuery不允许你出于兼容性原因这样做。不支持addEventListener的IE浏览器也不支持捕获阶段的绑定。