我不希望點擊某些孩子以外的其他孩子,並且父母div本身觸發任何事件。如何檢查點擊是否直接在元素或其子元素中?
請看到這一點,這並不做我想做的:
https://jsfiddle.net/k12e8rgt/3/
$(document).ready(function() {
$('#parent').on('click', function(event) {
alert("you clicked directly on me!");
});
});
我不希望點擊某些孩子以外的其他孩子,並且父母div本身觸發任何事件。如何檢查點擊是否直接在元素或其子元素中?
請看到這一點,這並不做我想做的:
https://jsfiddle.net/k12e8rgt/3/
$(document).ready(function() {
$('#parent').on('click', function(event) {
alert("you clicked directly on me!");
});
});
可以使用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>
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>
https://jsfiddle.net/k12e8rgt/5/ – adeneo