gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:23:00 24 4
gpt4 key购买 nike

以下代码基本上显示/隐藏段落标签,我必须重新声明 paras 变量。这是因为我动态地将 button 注入(inject)到 DOM 中,还是与范围有关?我怎样才能更好地构建这个标记?

// vars
var revealContainer = document.querySelector('.reveal-more');
var paras = revealContainer.querySelectorAll('p');
var status = true;

// return
if (paras && paras.length <= 3) return;

// generate show more link
revealContainer.innerHTML += '<button class="button--text reveal-more__btn">Read more</button>';
var revealBtn = revealContainer.querySelector('.reveal-more__btn');

// click event
revealBtn.addEventListener('click', function () {

var paras = revealContainer.querySelectorAll('p');

// toggle show/hide class
for (var i = 0; i < paras.length; i++) {
var p = paras[i];
p.classList.toggle('is-shown');
}

// check status
if (status) {
this.textContent = 'Read less';
status = false;
} else {
this.textContent = 'Read more';
status = true;
}

});

最佳答案

您可以使用live HTMLCollection返回者 .getElementsByTagName()而不是静态 NodeList返回者 .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>

关于javascript - 事件监听器内的范围问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54074545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com