如果将onclick事件绑定到父级,jQuery中是否有一种方法可以告诉哪个孩子被点击了?
例如:
$('#daddy').click(function () {
// if($("#son").isClicked()){return true;}
//return false;
});
Run Code Online (Sandbox Code Playgroud)
并且标记看起来像:
<div id="daddy">
<span id="son"></span>
<span id="daughter"></span>
</div>
Run Code Online (Sandbox Code Playgroud)
Fis*_*rdo 23
传递给的事件处理程序click将接收一个event对象作为其第一个参数.该target事件(即发起事件的元素)将被指定有.
这是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>
Run Code Online (Sandbox Code Playgroud)
您可以使用event.target来确定点击了什么:
$('#daddy').click(function (e) {
alert(e.target.id); // The id of the clicked element
});
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子。