Javascript Div上的jQuery点击事件,除了子Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10160219/
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 Click Event On Div, Except Child Div
提问by Justin
I have the following HTML:
我有以下 HTML:
<div class="server" id="32">
<a>Server Name</a>
<div class="delete-server">X</div>
</div>
I am trying to make it so when users click the server
div it brings up an edit dialog. The problem is simply doing:
我试图做到这一点,当用户单击server
div 时,它会显示一个编辑对话框。问题只是在做:
$(".server").click(function () {
//Show edit dialog
});
Does not work, because if they click the X which is delete, it brings up the edit dialog. How can make the entire div server
have the click event except the delete-server
div.
不起作用,因为如果他们单击要删除的 X,则会弹出编辑对话框。如何让整个 divserver
具有除delete-server
div之外的点击事件。
回答by Joseph Silber
$(".server").on('click', ':not(.delete-server)', function (e) {
e.stopPropagation()
// Show edit dialog
});
Here's the fiddle: http://jsfiddle.net/9bzmz/3/
这是小提琴:http: //jsfiddle.net/9bzmz/3/
回答by gdoron is supporting Monica
回答by Tomalak
There is an alternative way to solve this:
有一种替代方法可以解决这个问题:
$(".server").click(function () {
// show edit dialog
});
$(".delete-server").click(function (event) {
// show delete dialog for $(this).closest(".server")
event.stopPropagation();
});
Just make sure a click event issued on .delete-server
does not bubble up to the parent element.
只要确保发出的点击事件.delete-server
不会冒泡到父元素。
回答by German Khokhlov
Only this works for me.
只有这对我有用。
js_object
is jQuery object for meta parent like a $('body')
js_object
是元父级的 jQuery 对象,例如 $('body')
jq_object.on('click', '.js-parent :not(.js-child-1, .js-child-2)', function(event) {
//your code
});
jq_object.on('click', '.js-child-1', function(event) {
//your code
});
jq_object.on('click', '.js-child-2', function(event) {
//your code
});
Fore your case:
Fore你的情况:
server — js-parent
服务器 — js-parent
delete-server — js-child-1
删除服务器 — js-child-1
jq_object.on('click', '.server :not(.delete-server)', function(event) {
//your code
});
jq_object.on('click', '.delete-server', function(event) {
//your code
});