【问题标题】:jQuery Event BubblejQuery 事件气泡
【发布时间】:2011-12-31 01:28:21
【问题描述】:

我在锚元素中附加了一个 mousedown 事件,它可以做很多事情。

我还有一个附加到文档的 mousedown 事件,并且由于冒泡,每当触发附加到锚点的事件时都会调用此事件。这不是我想要的。

我可以延迟绑定事件吗? 我不想使用 stopPropagation。

$('a').mousedown ->
  ...
  openWindow()
  $(document).mousedown ->
     ...
     closeWindow()

编辑

我创建了一个 hack

$.fn.onBubble = (events, selector, data, handler) ->
    setTimeout => 
        this.on events, selector, data, handler 
    , 0

工作但喜欢很丑

【问题讨论】:

  • 你将无法阻止冒泡没有 event.stopPropagation(),据我所知......
  • 当我声明它时,我只想停止当前的气泡

标签: javascript jquery coffeescript


【解决方案1】:

正如其中一位 cmets 所提到的,阻止事件冒泡的唯一方法是使用 stopPropagation。也就是说,如果有两种情况您确实想要防止冒泡和其他情况,您可以将event.stopPropagation()放入if语句中: p>

$(...).mousedown(function(event) {
    if(/* some condition */) { event.stopPropagation(); }
});

或者,您可以向附加到文档的事件处理程序添加条件。例如:

$(document).mousedown(function(event) {
    if($(event.target).is("a")) {
        return; // if the element that originally trigged this event
                // (i.e. the target) is an anchor, then immediately return.
    }
    /** code that runs if event not from an anchor **/
});

这个 sn-p 使用$.fn.is 来确定事件是否由锚点触发。如果它是由锚生成的,代码会立即返回,这实际上忽略了事件气泡。

编辑回应评论:

如果我理解正确,如果用户单击窗口中的任何内容,您想关闭窗口。在这种情况下,试试这个:

function whenWindowOpens { // Called when the window is opened
    var windowElement; // Holds actual window element (not jQuery object)
    $(document).bind("mousedown", function(event) {
        if($.contains(windowElement, event.target)) {
            return; // Ignore mouse downs in window element
        }

        if($(event.target).is(windowElement)) {
            return; // Ignore mouse downs on window element
        }

        /** close window **/

        $(this).unbind(event); // detaches event handler from document
    });
}

这基本上是上面建议的第二种解决方案的变体。前两个 if 语句确保鼠标按下不会发生在(使用 $.contains)或(再次使用 $.fn.iswindowElement 上。当两个语句都为假时,我们关闭窗口并取消绑定当前事件处理程序。请注意,$.contains 只接受原始 DOM 元素 -- not jQuery 对象。要从 jQuery 对象中获取原始 DOM 元素,请使用 $.fn.get

【讨论】:

  • 我不想使用 stopPropagation,因为它是一个应用程序。我只想打开一个窗口并在文档中附加一个事件以将其关闭。我可以使用覆盖层来做到这一点,但我也不想
  • 我想我更能理解你的问题。我已经编辑了我的答案以添加一个可能的解决方案。
猜你喜欢
  • 1970-01-01
  • 2016-03-28
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
  • 2011-10-20
  • 1970-01-01
相关资源
最近更新 更多