jQuery事件泡泡

时间:2011-12-30 16:03:06

标签: javascript jquery coffeescript

我在一个锚元素中附加了一个mousedown事件,它可以执行许多操作。

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

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

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

修改

我创建了一个黑客

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

工作,但非常难看

1 个答案:

答案 0 :(得分:3)

正如其中一条评论所提到的,阻止事件冒泡的唯一方法是使用stopPropagation。也就是说,如果有要防止冒泡的条件和的其他条件,则可以将event.stopPropagation()放入if语句中:

$(...).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 **/
});

此代码段使用$.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元素 - 而不是 jQuery对象。要从jQuery对象获取原始DOM元素,请使用$.fn.get