jQuery 防止点击事件jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8464640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent click event jquery
提问by Cecil Theodore
I have a number of list items that contain images within links. When one of these links is clicked, I want to get containing li
's rel attribute only, without following the click event though. Following the event through currently opens the link image up in a new page which I do not want.
我有许多在链接中包含图像的列表项。当单击这些链接之一时,我只想获得li
contains 的 rel 属性,但不遵循单击事件。通过当前的事件在我不想要的新页面中打开链接图像。
I have tried return false;
within my function but this doesnt work (see below). I have also tried this on the actual link in the mark up but I would rather not do this as this isn't best practice.
我return false;
在我的函数中尝试过 ,但这不起作用(见下文)。我也在标记中的实际链接上尝试过这个,但我宁愿不这样做,因为这不是最佳实践。
$('a.main-img').click(function (){
var liRel = $(this).closest('li').attr('rel');
var relNumber = $('#banner-holder').find('img').attr('id', liRel);
rotatePics(relNumber);
return false;
});
回答by Crab Bucket
Note though that preventDefault
wont stop the event from bubbling up the DOM and being actioned by and event on one of the parents. The function event.StopPropagation
will do that. PreventDefault stops the default action of the link. Return false actually does both so using preventDefault won't be an exact functional replication of return false.
请注意,虽然这preventDefault
不会阻止事件冒泡 DOM 并由其中一个父级上的事件进行操作。该功能event.StopPropagation
将做到这一点。preventDefault 停止链接的默认操作。Return false 实际上两者兼而有之,因此使用 preventDefault 不会是 return false 的精确功能复制。
This SO questiongives a comprehensive run through.
这个SO 问题给出了一个全面的贯穿。
Probably won't make a difference in this case but when it does it has really confused me in the past
在这种情况下可能不会有所作为,但是当它发生时,它过去真的让我感到困惑
回答by defau1t
You should learn about event.preventDefault()
and event.stopPropagation()
你应该了解event.preventDefault()
和event.stopPropagation()
回答by Ryan Casas
http://api.jquery.com/event.preventDefault/
http://api.jquery.com/event.preventDefault/
Read, here you have an example.
阅读,这里有一个例子。
EDIT:Your corrected code will be like this:
编辑:您更正后的代码将如下所示:
$('a.main-img').click(function (event){
event.preventDefault();
var liRel = $(this).closest('li').attr('rel');
var relNumber = $('#banner-holder').find('img').attr('id', liRel);
rotatePics(relNumber);
});
回答by Sudhir Bastakoti
Try:
尝试:
$('a.main-img').click(function (evt){ evt.preventDefault();