Javascript $(document).on('click', selector, function() ) 结合 :not
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11050704/
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
$(document).on('click', selector, function() ) combined with :not
提问by Plexus81
I've got several list items, when I click on the item I want the browser to redirect to ".title > a" link (href). But I don't want any event on the "notThis" selector.
我有几个列表项,当我单击该项时,我希望浏览器重定向到“.title > a”链接(href)。但我不希望“notThis”选择器上有任何事件。
see the example http://jsfiddle.net/VTGwV/29/
参见示例 http://jsfiddle.net/VTGwV/29/
<div class="item">
<div class="title">
<a href="www.jsfiddle.net">jsfiddle.net</a>
</div>
<div> djf?ljdsaf?ljdsf a</div>
<div> djf?ljdsaf?ljdsf a</div>
<div> djf?ljdsaf?ljdsf a</div>
<div class="notThis">
<a href="/test.html">link1 </a>
<a href="/test2.html">link2</a>
</div>
?
?
script
脚本
?$(document).on('click', '.item', function(event) {
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});?
I've tried :not('.notThis') without any luck.
我试过 :not('.notThis') 没有任何运气。
ChangesThanks for all the answers, but I found another problem. If I have a event handler on the whole item , I can't manage to click on the link in "notThis" selector, because it returns only "false". Isn't there a way to use .not / :not combined with $(document).on('click', -------)
更改感谢所有答案,但我发现了另一个问题。如果我在整个项目上有一个事件处理程序,我将无法点击“notThis”选择器中的链接,因为它只返回“false”。有没有办法使用 .not / :not 与 $(document).on('click', -------) 结合使用
回答by Felix Kling
You can test whether the click event originated from within the .notThis
element (or the element itself):?
您可以测试单击事件是否源自.notThis
元素内部(或元素本身):?
$(document).on('click', '.item', function(event) {
if($(event.target).closest('.notThis').length > 0) {
return false; // if you want to ignore the click completely
// return; // else
}
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});?
I also think you can use this
instead of event.currentTarget
.
我也认为您可以使用this
代替event.currentTarget
.
回答by akalucas
Your syntax is wrong, just use the selector like this:
您的语法错误,只需像这样使用选择器:
Example
例子
$("div.item > div:not(.notThis)").click(function(){
window.location.href = $(this).find('.title > a').attr('href');
});
回答by Artem Koshelev
var clickable = $('.item').find('div').not('.notThis');
$(clickable).on('click', function(event) {
alert($(this).parent().find('.title a').attr('href'));
});