Javascript 一个div上的Fire click事件,不包括一个子div及其';后代
里面还有其他的儿童版。那些也有儿童沙发Javascript 一个div上的Fire click事件,不包括一个子div及其';后代,javascript,jquery,ajax,Javascript,Jquery,Ajax,里面还有其他的儿童版。那些也有儿童沙发 <div class="parent"> <div class="child_1">//children elements</div> <div class="child_1">//children elements</div> <div class="child_1">//children elements</div> <div class="child_1">
<div class="parent">
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
</div>
但是,当我单击child_1div及其后代时,click事件会起作用
这里有什么问题?请帮忙
更新
这里我有另一个关于child_1
jQuery(".child_1").click(function(event) {
});
我想应该是这样
jQuery(".parent, .parent *").not(".child_1").click(function(event) {
});
试试这个():
(编辑+更新小提琴)
我发现了一个缺陷。此版本检查单击的元素是否在类为“exclude”的元素中:
<div class="parent">
<div class="child_1 exclude">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
</div>
jQuery(".parent").click(function(event)
{
if ($(event.target).closest('.exclude').length>0) return false;
alert('hi');
});
//子元素
//子元素
//子元素
//子元素
jQuery(“.parent”)。单击(函数(事件)
{
if($(event.target).closest('.exclude').length>0)返回false;
警报(“hi”);
});
你应该这样做
$('.parent').on('click', function () {
// do your stuff here
}).find('.child_1').on('click', function (e) {
e.stopPropagation();
});
这里有一个fiddle您仍然必须捕获要排除的元素上的单击事件,否则单击将冒泡到
.parent
元素
使用最近的
方法检查单击的元素是否是类为.child_1
的元素或其子元素。使用stopPropagation
防止事件冒泡:
$('.parent,.parent *').click(function(e){
if ($(this).closest('.child_1').length > 0) {
alert('in child_1');
} else {
alert('not in child_1');
}
e.stopPropagation();
});
演示:有点老问题,但我想我会放弃我的决心,以防它对其他人有帮助 这和我做的差不多。此示例使用您的标记:
$('.parent').on('click', function(e) {
var $target = $(e.target);
if (!$target.parents('.child_1').length && !$target.hasClass('child_1')) {
// do what you need on the parent's click event
// add 'e.preventDefault()' here if you need
}
// no need to prevent default or stop propagation here
// this will allow click events on child elements to work
});
你能用JSfiddle发送你的例子吗?我使用了exclude类,因为你所有的孩子都叫child_1。您还可以使用
$(event.target).closest('.parent').children().get(0)=event.target
。如果您没有明确取消其他子项可能具有的任何单击函数中的任何传播,则仅在.parent
上使用单击事件将可以正常工作。
$('.parent').on('click', function(e) {
var $target = $(e.target);
if (!$target.parents('.child_1').length && !$target.hasClass('child_1')) {
// do what you need on the parent's click event
// add 'e.preventDefault()' here if you need
}
// no need to prevent default or stop propagation here
// this will allow click events on child elements to work
});