我在div里面有一个div。如果单击了内部div(closeme div),我不想运行其他div(容器div)单击事件。我怎么能这样做?
HTML
<div id="container">
content
<div id="closeme"></div>
</div>
JS
$(document).on('click', '[id="container"]' ,function(){
alert("I am clicked");
}
$(document).on('click', '[id="closeme"]' ,function(){
alert("I am clicked");
}
答案 0 :(得分:2)
$(document).on('click', '[id="container"]', function(e) {
e.stopPropagation();
alert("I am container");
})
$(document).on('click', '[id="closeme"]', function(e) {
e.stopPropagation();
alert("I am closeme");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
content
<div id="closeme">qwe</div>
</div>
描述:防止事件冒泡DOM树,防止任何父处理程序被通知事件。
答案 1 :(得分:2)
执行if以测试目标是否为#closeme
$(document).on('click', '[id="closeme"]', function(event) {
if ($(event.target).is('[id="closeme"]')) {
alert("coloseme clicked");
}
});
答案 2 :(得分:1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="container">
content
<div id="closeme">Inner Div</div>
</div>
</body>
<script>
$(document).on('click', '[id="container"]', function(event) {
alert("container clicked");
});
$(document).on('click', '[id="closeme"]', function(event) {
event.stopPropagation();
alert("coloseme clicked");
});
</script>
</html>