关于javascript:event.stopPropagation停止实时事件的传播,尽管不应这样做

event.stopPropagation stops propagation of live events, although it should not

的文档说event.stopPropagation不应停止实时事件的传播(http://api.jquery.com/event.stopPropagation)。但是,它对我来说却恰恰相反。试试这个:http://jsfiddle.net/PSYg8。单击红色Div会触发附加到html元素的实时事件。


该文档告诉您的是,无法从live处理程序调用stopPropagation

因为jQuery通过侦听所有传播到<html>元素的所有事件,然后查看触发元素是否与您的原始选择器匹配,从而实现了live事件,因此停止从常规事件处理程序传播到该元素可以防止该事件到达live处理程序。

编辑:如果您不清楚DOM事件和事件传播的工作方式,QuirksMode对捕获和冒泡模型进行了精彩的分析,Microsoft提供了一个很棒的页面,可让您直观地了解W3C中事件传播的工作方式,经典和IE模型。


Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events

含义

1
2
3
4
$('html').live('click', function(e){
    e.stopPropagation(); // does nothing
    alert('html');
});

您误解了文档。当您停止在click事件上传播时,它不会冒泡到实时事件。


您正在交换项目。在.live内部,不能使用stopPropagation。因此,例如,这确实会生成两个警报:http://jsfiddle.net/PSYg8/1/。

1
2
3
4
5
6
7
8
9
10
$(document).ready(function(){
    $('html').live('click', function(){
        alert('html');
        event.stopPropagation();
    });

    $('div').click(function(event){
        alert('div');
    });
});

.click(.bind)内部,stopPropagation无缝运行。它只是阻止div事件冒泡到html元素。