4

我的代码是

<div id="hello">
<div>A</div></div>
<script>
$(function(){
$(document).mousedown(function(event){alert(event.target.id);});
});</script>

现在,当我单击 div id“hello”时,它会提示 null,因为它正在获取中心 div 的 id,但我想要外部 div 的 id。如何实现?

4

4 回答 4

3

因为目标是最里面的 div

试试这个

event.target.parentNode.id
于 2012-05-18T12:28:19.327 回答
1

尝试稍微更改您的代码:

<div id="hello">
<div>A</div></div>
<script>

$(function(){
    //You can change the selector to what suits you best here
    $("body>div").mousedown(function(event){alert(event.currentTarget.id);});

    //it is safer to use currentTarget when you have nested elements
});</script>
于 2012-05-18T12:29:06.207 回答
0

采用event.target.parentNode.id

于 2012-05-18T12:27:05.933 回答
0

您应该将事件绑定到您感兴趣的 div。在您的情况下,您应该将其绑定到$('#hello')

如果您有多个 div 想要绑定该事件,请向它们添加一个类,并将 mousedown 事件绑定到该类,并在您的回调函数中检查 event.target 的 id。

于 2012-05-18T12:29:31.470 回答