How can affect click event only ul tag not all li with jQuery?
用jQuery如何只影响点击事件ul标签不都是li ?
<!-- HTML -->
<ul class="wrap">
<li>test1</li>
<li>test2</li>
<li>test3</li>
</ul>
I tried jquery like this.But it doesnt work.
我试过jquery,像这样。但它不工作。
//Javascript
jQuery("ul.wrap").not(jQuery("ul > li")).click(function(){
//fire only ul
});
How can we do this?
我们怎么做呢?
2 个解决方案
#1
2
Events 'bubble' up the DOM to their parent elements. What you need to do is attach the event to the ul
, and another event on the child li
elements which uses stopPropagation()
:
事件“冒泡”DOM到它们的父元素。您需要做的是将事件附加到ul,以及使用stopPropagation()的子li元素上的另一个事件:
jQuery("ul.wrap")
.on('click', function(){
// do something...
})
.on('click', 'li', function(e) {
e.stopPropagation();
});
#2
4
You can simply do it with this code:
你可以用下面的代码来做:
jQuery('.wrap').click(function (event) {
if ( !$(event.target).is( "li" ) ) {
console.log('ul clicked!');
}
});
You can see an example with background colors that shows the ul and the li here: http://jsfiddle.net/S67Uu/2/
您可以看到一个带有背景颜色的示例,其中显示了ul和li: http://jsfiddle.net/s67u/2/。
#1
2
Events 'bubble' up the DOM to their parent elements. What you need to do is attach the event to the ul
, and another event on the child li
elements which uses stopPropagation()
:
事件“冒泡”DOM到它们的父元素。您需要做的是将事件附加到ul,以及使用stopPropagation()的子li元素上的另一个事件:
jQuery("ul.wrap")
.on('click', function(){
// do something...
})
.on('click', 'li', function(e) {
e.stopPropagation();
});
#2
4
You can simply do it with this code:
你可以用下面的代码来做:
jQuery('.wrap').click(function (event) {
if ( !$(event.target).is( "li" ) ) {
console.log('ul clicked!');
}
});
You can see an example with background colors that shows the ul and the li here: http://jsfiddle.net/S67Uu/2/
您可以看到一个带有背景颜色的示例,其中显示了ul和li: http://jsfiddle.net/s67u/2/。