我有一个点击绑定为元素的实时。处理程序在执行后返回false,但如果该元素碰巧是A标记,那么也不会遵循该链接,这是不可接受的......
$('*').live('click', function(){
// lots of code here
return false;
});
现在,如果单击的元素具有类似A>img
的路径并且单击了图像,则永远不会遵循A.我不希望click事件再传播。
我该如何实现这个目标?
编辑:
我的应用程序必须将事件绑定到*。此外,可以对任何元素进行点击,而不仅仅是A。因此,所提到的解决方案都不适合我希望实现的目标。
答案 0 :(得分:2)
您正在寻找的是preventDefault()
$('*').live('click', function(e){
// lots of code here
e.preventDefault();
return false; // Don't think this is necessary
});
我还想说,将事件附加到所有元素可能不是一个好主意。
通过专门附加A
代码,您可以获得更好的服务:
$('a').click(function(e){
// lots of code here
e.preventDefault();
return false;
});
答案 1 :(得分:0)
尝试:
if($(this).tagName == 'A')
return true; // perhaps even { do nothing }
else
return false;
这可能不是获取标记名的确切代码,请参阅此How to extend jQuery to make it easier to retrieve the tagName。
另见:http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
答案 2 :(得分:0)
我不会将点击功能绑定到*
。您可以将其绑定到body
元素;单击将从单击的元素传播到body
元素。您可以检查最初单击的元素,如下所示:
$("body").live("click", function (e) {
if ($(e.originalEvent.target).is("a")) {
return false;
}
});
话虽如此,你仍然可以这样做:
$("*").live("click", function () {
if ($(this).is("a") == false) {
return false;
}
});