2016-07-24 96 views

回答

3

可以使用event.target

例子:

$(document).ready(function() { 
 
    $("div").on("click", function(event) { 
 
    alert("You click on : " + event.target.tagName) 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div>this is Div 
 
    <p>This is p</p> 
 
</div>

+0

我不知道如何帮助,您可以详细点吗? “不在这里”的孩子可以有很多孩子,在这种情况下,event.target将是其中的一个,所以我不能简单地比较一下event.target == .not.here。 – Lao

+1

你可以给div一个唯一的id/class/data属性,并且可以通过event.target对象获得,因为这是实际点击的dom元素...然后你可以知道属性是你想要的,并触发如果存在则采取行动,如果不存在则采取行动 – Stu

1
  • 将类分配给它们将成为元素ignored
  • 使用.hasClass()来检测rmine是否有任何匹配的元素被分配给定的类

$('#parent').on('click', function(event) { 
 
    if ($(event.target).hasClass('ignore')) { 
 
    alert("Ignore !"); 
 
    } else { 
 
    alert("Do something!"); 
 
    } 
 
});
#parent { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: blue; 
 
    color: white; 
 
} 
 
#child2 { 
 
    background-color: white; 
 
    color: red; 
 
    margin: 10px; 
 
} 
 
#child1 { 
 
    background-color: white; 
 
    color: green; 
 
    margin: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div id="parent">it should trigger here 
 
    <div id="child1">and here</div> 
 
    <div id="child2" class="ignore">but not here, and there are many of this kind</div> 
 
</div>

如果那里设立ids它们将成为ignored,使用event.target.id属性和反对测试值!

$('#parent').on('click', function(event) { 
 
    if (event.target.id === 'child2' || event.target.id === 'child3') { 
 
    alert("Ignore !"); 
 
    } else { 
 
    alert("Do something!"); 
 
    } 
 
});
#parent { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: blue; 
 
    color: white; 
 
} 
 
#child2 { 
 
    background-color: white; 
 
    color: red; 
 
    margin: 10px; 
 
} 
 
#child3 { 
 
    background-color: white; 
 
    color: red; 
 
    margin: 10px; 
 
} 
 
#child1 { 
 
    background-color: white; 
 
    color: green; 
 
    margin: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div id="parent">it should trigger here 
 
    <div id="child1">and here</div> 
 
    <div id="child2">but not here, and there are many of this kind</div> 
 
    <div id="child3">but not here, and there are many of this kind</div> 
 
</div>