0

我将如何编写一个 jquery 操作,以便当单击网页上的任何内容时,除了某个 div 之外,查询执行一个功能?

4

2 回答 2

5

这是我的方式:

$(document).on("click", function(){
    alert('foo');
});
$('#yourdiv').on("click", function(event){
    event.stopPropagation();
})

http://jsfiddle.net/v3N2T/5/

这个想法是您将点击事件放在整个页面上,然后在您不想执行该操作的元素上捕获点击,并阻止它将点击事件传播到文档点击事件。

It might interact badly if you have any other click event stuff going on but you may have that problem anyway...

P.S. Credit to Adrian for his original answer that allowed me to develop this solution much more quickly by just modifying his. :)

于 2012-11-07T15:55:27.787 回答
2

从 jQuery 1.7 开始,on()鼓励使用:

$(document).on("click", ":not(#yourdiv)", function(){
    //do your thing

    //important: return false to avoid repeating the call for each DOM element in
    //the hierarchy
    return false;
})

请参阅更新的小提琴:http: //jsfiddle.net/adrianonantua/v3N2T/8/

现在,有一个警告:在小提琴示例中,似乎正在单击不需要的 div。但是,实际上,click 事件是由其父级触发的。

于 2012-11-07T15:33:49.917 回答