Jquery:停止传播?

我已经添加了stopPropagation,但是,我仍然连续获得两个弹出窗口。 这比以前更好,其中有一个元素被点击了20个弹出窗口….是否有更好的方法或我错过了什么?

$(top.document).ready(function () { $("*").click(processAction); }); function processAction(e) { var clicked = e.target; e.stopPropagation(); alert(clicked.tagName); e.stopPropagation(); switch (clicked) { case "A": //execute code block 1 break; case "INPUT": //execute code block 2 break; default: //code to be executed if n is different from case 1 and 2 } }; 

我要说绝对不要在每个元素上放置一个点击处理程序。 正如@Rin所述,您可以通过标签或其他选择器分配它们。

如果你真的想以这种方式处理页面上的所有点击,我建议你在document上放置一个处理程序,让点击事件冒泡到那个。

这样效率更高,并且不需要执行e.stopPropagation()

示例: http //jsfiddle.net/y6hry/

 $(top.document).ready(function () { // All clicks on the page will bubble up to the document // and fire the handler. $(document).click(processAction); }); function processAction(e) { var clicked = e.target; alert(clicked.tagName); switch (clicked.tagName) { case "A": //execute code block 1 break; case "INPUT": //execute code block 2 break; default: //code to be executed if n is different from case 1 and 2 } }; 

使用

 $('*').each(map, function(key, value) { $(this).click(processAction); }); 

代替;

我的小建议:用ainput替换* 。 现在你的代码会更简单,你可以删除开关。 (我在开关中看到你检查点击了哪个元素)。