如何确定孩子是否在 Jquery 中被点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9504997/
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
How to determine if child was clicked in Jquery
提问by Du3
Is there a ways in jQuery to tell which child was clicked if the onclick event was binded to the parent?
如果 onclick 事件绑定到父级,jQuery 中有没有办法判断哪个子级被点击?
For instance:
例如:
$('#daddy').click(function () {
// if($("#son").isClicked()){return true;}
//return false;
});
and the markup looks like:
和标记看起来像:
<div id="daddy">
<span id="son"></span>
<span id="daughter"></span>
</div>
回答by FishBasketGordo
The event handler you pass to click
will receive an event
object as its first argument. The target
of the event (i.e. the element that initiated the event) will be specified there.
您传递给的事件处理程序click
将接收一个event
对象作为其第一个参数。该target
事件(即发起事件的元素)将被指定有。
Here's an example from the jQuery documentation:
这是jQuery 文档中的一个示例:
<!DOCTYPE html>
<html>
<head>
<style>
span, strong, p {
padding: 8px; display: block; border: 1px solid #999; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="log"></div>
<div>
<p>
<strong><span>click</span></strong>
</p>
</div>
<script>
$("body").click(function(event) {
$("#log").html("clicked: " + event.target.nodeName);
});
</script>
</body>
</html>
回答by Pat
You can use the event.targetto determine what was clicked:
您可以使用event.target来确定点击了什么:
$('#daddy').click(function (e) {
alert(e.target.id); // The id of the clicked element
});
Here's a simple example.
这是一个简单的例子。
回答by Eric Hodonsky
This should be a different perspective at least:
这至少应该是一个不同的观点:
$('#parent').on("click", function(evt) {
evt.stopPropagation();
if($.inArray(evt.currentTarget, $(this).children())){
console.log(evt.currentTarget);
}
});
回答by frictionlesspulley
回答by blackpla9ue
Try this for an alternative
试试这个
$('#daddy span').click(function () {
var clicked = $(this).attr('id');
if(clicked == "son"){
return true;
}
return false;
});
回答by Luca C.
use event.target
to get the really clicked node:
用于event.target
获取真正点击的节点:
$('#daddy span').on('click',function(event){
if(event.target.nodeName=='BUTTON'){//Was clicked a button
....
}
if(event.target.id=='id'){//Was clicked #id
....
}
...
});