事件监听器内部的范围问题?

时间:2019-01-07 12:34:02

标签: javascript

以下代码基本上显示/隐藏了段落标签,我不得不重新声明photoPlant(arg)变量。这是因为我正在将paras动态注入到DOM中,还是与范围有关?我如何更好地构造此标记?

button

2 个答案:

答案 0 :(得分:2)

You can use the live HTMLCollection returned by .getElementsByTagName() instead of the static NodeList returned by .querySelectorAll()

The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

var paragraphs = document.getElementById("container").getElementsByTagName("p");
console.log(paragraphs.length);

setInterval(function() {
  document.getElementById("container").insertAdjacentHTML("beforeend", "<p>p</p>");
}, 1000);

setInterval(function() {
  console.log(paragraphs.length);
}, 2000);
<div id="container"></div>

答案 1 :(得分:0)

下面是一个非常简单的代码段,它使用纯Javascript演示了委托事件,而不是使用jQuery。

在这里您可以看到我已将事件监听器附加到ID为elements的div上,然后它将在此监听click事件,为防万一,使用了一个简单的matches您还有其他您不感兴趣的元素。

document.querySelector("#elements").addEventListener("click", (e) => {
  if (!e.target.matches('.element')) return
  console.log(`Clicked ${e.target.innerText}`);
});
.element {
  border: 1px solid black;
  margin: 5px;
}
<div id="elements">
  <div class="element">1</div>
  <div class="element">2</div>
  <div class="element">3</div>
  <div>Clicking this does nothing.</div>
</div>