以下代码基本上显示/隐藏了段落标签,我不得不重新声明photoPlant(arg)
变量。这是因为我正在将paras
动态注入到DOM中,还是与范围有关?我如何更好地构造此标记?
button
答案 0 :(得分:2)
You can use the live HTMLCollection
returned by .getElementsByTagName()
instead of the static NodeList
returned by .querySelectorAll()
The
getElementsByTagName
method ofDocument
interface returns anHTMLCollection
of elements with the given tag name. The complete document is searched, including the root node. The returnedHTMLCollection
is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to calldocument.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>