[英]JQuery selector to exclude child elements
I'm using this click method to reveal additional classes inside a .tile
我正在使用此click方法来显示
.tile
其他类
var $tiles = $('.tile');
$tiles.on('click', function(){
var $this = $(this);
$this.toggleClass('large'); // change layout of tile
$this.children('.details').toggle(); // display additional info
})
Since a .tile
may contain links, I'd like to limit the click functionality. 由于
.tile
可能包含链接,因此我想限制点击功能。 I don't want the function to trigger when a link inside .tile
is clicked. 我不希望该函数在单击
.tile
的链接时触发。
Edit: While @antyrant's answer is working for normal links, I noticed in my example the problem persists with on of the links that uses fancyBox. 编辑: @antyrant的答案适用于普通链接时,我在示例中注意到使用fancyBox的链接上的问题仍然存在。
This is what my HTML looks like: 这是我的HTML外观:
<div class="tile">
<ul class="details">
<li><a class="download"> href="#">Download</a></li>
<li><a class="fancybox-media" href="#">Video</a></li>
</ul>
</div>
Clicking the download link works fine, but the fancyBox will not work! 单击下载链接可以正常工作,但是fancyBox将不起作用!
Edit 2: See this jsFiddle for a working example. 编辑2:有关工作示例,请参见此jsFiddle 。
You need to stop events propagation on child elements, for example: 您需要停止事件在子元素上的传播 ,例如:
$tiles.find( 'a' ).click( function( e ) {
e.stopPropagation();
});
UPDATE: If this can be done as you use some plugins for example you can check if event
target
has your base class: for example: 更新:如果例如使用某些插件时可以完成此操作,则可以检查
event
target
是否具有您的基类:例如:
$('.tile').on('click', function ( e ) {
if( !$( e.target ).hasClass( 'tile' ) ) {
return true;
}
//...
see jsFiddle demo . 参见jsFiddle演示 。
@antyrat is correct, stopping propagation on the anchors will achieve your goal, but that requires binding another event that isn't really necessary. @antyrat是正确的,停止在锚点上的传播将实现您的目标,但是这需要绑定另一个并非必需的事件。 Another option would be to look at the target on the event passed in to your handler.
另一个选择是查看传递给处理程序的事件的目标。
$tiles.on( 'click', function( e ) {
if( !$( e.target ).is( 'a' ) ) { // if the element clicked is not an anchor.
// do stuff
}
});
EDIT: Here's a fiddle demonstrating this working using the updated html provided above. 编辑: 这是一个小提琴,使用上面提供的更新的html演示了这项工作。
stopPropagation() will stop your child event from bubbling up, and being caught by the listener on the parent element. stopPropagation()将阻止您的子事件冒泡,并被父元素上的侦听器捕获。
var $tiles = $('.tile');
$tiles.on('click', function () {
console.log('clicked');
})
$('a', $tiles).on('click', function (e) {
e.stopPropagation(); //Prevents event from bubbling up
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.