我有几个列表项,当我单击我希望浏览器重定向到".title> a"链接(href)的项目时。但我不希望"notThis"选择器上有任何事件。
查看示例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>
脚本
$(document).on('click', '.item', function(event) {
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});
我试过:not('.notThis'),但没有任何运气。
变化感谢您的所有答案,但我发现了另一个问题。如果我在整个项目上有一个事件处理程序,我无法单击"notThis"选择器中的链接,因为它只返回"false"。有没有办法将 .not/:not 与 $(document).on('click', -------) 结合使用
您可以测试点击事件是否源自.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');
});
我也认为你可以用this
代替event.currentTarget
.
你的语法是错误的,只需像这样使用选择器:
例
$("div.item > div:not(.notThis)").click(function(){
window.location.href = $(this).find('.title > a').attr('href');
});
> http://jsfiddle.net/Lcg49/4/
var clickable = $('.item').find('div').not('.notThis');
$(clickable).on('click', function(event) {
alert($(this).parent().find('.title a').attr('href'));
});