Cap*_*ack 188 jquery events onclick
我有一个带有分类的DIV foobar,以及DIV内部的几个DIV,这些DIV没有被删除,但我想他们继承了这个foobar类:
$('.foobar').on('click', function() { /*...do stuff...*/ });
Run Code Online (Sandbox Code Playgroud)
我想要只在点击DIV中的某个地方而不是在其子DIV上点火时才开启.
小智 412
如果e.target元素与元素相同this,则表示您没有点击后代.
$('.foobar').on('click', function(e) {
if (e.target !== this)
return;
alert( 'clicked the foobar' );
});Run Code Online (Sandbox Code Playgroud)
.foobar {
padding: 20px; background: yellow;
}
span {
background: blue; color: white; padding: 8px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='foobar'> .foobar (alert)
<span>child (no alert)</span>
</div>Run Code Online (Sandbox Code Playgroud)
hob*_*key 51
如果您不介意只针对较新的浏览器,还有另一种方法可行.只需添加CSS即可
pointer-events: none;
Run Code Online (Sandbox Code Playgroud)
对于想要捕获点击的div的任何孩子.这是支持表
http://caniuse.com/#feat=pointer-events
ori*_*ori 26
你可以使用鼓泡对你有利:
$('.foobar').on('click', function(e) {
// do your thing.
}).on('click', 'div', function(e) {
// clicked on descendant div
e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
Jas*_*per 19
//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
event.stopPropagation();
//you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});
Run Code Online (Sandbox Code Playgroud)
这将停止click事件在元素的任何子元素上的传播(冒泡),.foobar因此事件将不会到达.foobar元素以触发其事件处理程序.
这是一个演示:http://jsfiddle.net/bQQJP/
Jen*_*ell 15
我没有得到公认的工作答案,但这似乎可以解决问题,至少在香草JS中是如此。
if(e.target !== e.currentTarget) return;
Run Code Online (Sandbox Code Playgroud)
小智 6
我遇到了同样的问题并提出了这个解决方案(基于其他答案)
$( ".newsletter_background" ).click(function(e) {
if (e.target == this) {
$(".newsletter_background").hide();
}
});
Run Code Online (Sandbox Code Playgroud)
基本上它说如果目标是 div 然后运行代码,否则什么都不做(不要隐藏它)
$(".advanced ul li").live('click',function(e){
if(e.target != this) return;
//code
// this code will execute only when you click to li and not to a child
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
187737 次 |
| 最近记录: |