javascript Jquery禁用div的点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22009428/
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
Jquery disable click event for div
提问by AME
Let's say I got a simple click event for a HTML div. If I click on the div it should trigger a fadeToggle.
假设我有一个 HTML div 的简单点击事件。如果我点击 div 它应该触发一个fadeToggle。
In that div I got another div with another trigger. On that click event it should do something but instead of doing the event it triggers the first event.
在那个 div 中,我得到了另一个带有另一个触发器的 div。在那个点击事件上,它应该做一些事情,但它不会触发第一个事件,而不是做这个事件。
How do I prevent event 1 from triggering if I want event2 to trigger?
如果我希望 event2 触发,如何防止 event 1 触发?
Event1 should trigger only if I don't press the clickevent on the second event everything else should trigger as usual.
只有当我没有在第二个事件上按下 clickevent 时,Event1 才应该触发,其他一切都应该像往常一样触发。
Thanks for your time
谢谢你的时间
HTML
HTML
<div id="1">
Event 1
<div id="2">
<div id="3">
but here is something as well event2
</div>
</div>
</div>
JavaScript
JavaScript
$("#1").click(function() {
$(this).slideToggle();
});
$("#3").click(function() {
$(this).css("background-color", "blue");
});
Fiddle: http://jsfiddle.net/VLcxJ/
回答by kamilkp
$("#3").click(function(e) {
e.stopPropagation();
$(this).css("background-color", "blue");
});
After that, clicks on #3 won't reach #2 or #1
之后,点击 #3 不会到达 #2 或 #1
回答by enguerranws
Use event.stopPropagation();
:
使用event.stopPropagation();
:
$("#e3").click(function(event) {
event.stopPropagation();
$(this).css("background-color", "blue");
});
See it working here : http://jsfiddle.net/bYn22/
看到它在这里工作:http: //jsfiddle.net/bYn22/
Note from jQuery API(I couldn't explain it better) : event.stopPropagation() > Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
来自 jQuery API 的注释(我无法更好地解释它): event.stopPropagation() >防止事件冒泡 DOM 树,防止任何父处理程序收到该事件的通知。
And note that your IDs can't begin with a number:)
请注意,您的 ID 不能以数字开头:)
回答by Ende Neu
$("#3").click(function(event) {
event.stopPropagation();
$(this).css("background-color", "blue");
});
Added Fiddle: http://jsfiddle.net/VLcxJ/1/
添加小提琴:http: //jsfiddle.net/VLcxJ/1/
回答by monu
Here is the solution
这是解决方案
$("#1").click(function() {
$(this).slideToggle();
});
$("#3").click(function(event) {
event.stopPropagation();
$(this).css("background-color", "blue");
});