身体事件未触发

时间:2017-05-27 12:55:21

标签: javascript html

这是代码:

<!DOCTYPE html>
<html>
<body onclick="myFunction(event)">

<p onclick="myFunction(event)">Click on a paragraph. An alert box will alert the element that triggered the event.</p>

<p><strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.</p>

<script>
function myFunction(event) { 
    alert(event.target.nodeName);
}
</script>

</body>
</html>

所以,当我点击<p>时,有两个弹出窗口都与P有关,但我们不应该有一个P和一个Body,因为onclick事件与<body>相关联标记

2 个答案:

答案 0 :(得分:1)

您的代码工作正确。它显示目标元素标记名称。它正确,因为您没有单击空体。有一些子元素是p所以它显示p。仅显示单击元素标记名称的文本。仅添加一个文本,不包含正文的任何​​元素直接文本。

function myFunction(event) { 
    alert(event.target.nodeName);
}
<body onclick="myFunction(event)">
its direct text of the body click here you get the body
<p onclick="myFunction(event)">Click on a paragraph. An alert box will alert the element that triggered the event.</p>

<p><strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.</p>


</body>

答案 1 :(得分:0)

event.target将是您实际点击的标记。