“div”中的“input”:如何为“div”注册“onclick”事件侦听器,而不是为“input”注册

use*_*220 0 javascript

我有一个div元素,里面有一个input元素。我想在单击div. 它工作正常,但问题是:input也检测到“点击” ,我不想。

document.getElementById("foo").addEventListener('click', function(event) {
  alert();
  event.stopPropagation();
})
Run Code Online (Sandbox Code Playgroud)
div {
  width: 300px;
  height: 300px;
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div id="foo">
<input>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

event.stopPropagation();在错误的事件中使用,这就是它不起作用的原因。stopPropagation防止事件冒泡,因此您需要在子事件中使用它。

尝试这个。

document.getElementById("foo").addEventListener('click', function(event) {
  if(event.target === event.currentTarget) {
    alert();
  }
})
Run Code Online (Sandbox Code Playgroud)
div {
  width: 300px;
  height: 300px;
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<div id="foo">
  <input>
</div>
Run Code Online (Sandbox Code Playgroud)