gpt4 book ai didi

javascript - 监听器未添加到创建的 div

转载 作者:行者123 更新时间:2023-11-30 20:31:18 25 4
gpt4 key购买 nike

所以我有以下称为 addPanels() 的函数,它向每个类为“accordion”的元素添加一个事件监听器

function addPanels(){
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}

var arrow = this.children[0].children[0];

if (panel.style.display === "block") {
arrow.src = "Iconos/arrow_up.png";
} else {
arrow.src = "Iconos/arrow_down.png";
}
});
}
}

然后我有这个:

$(document).ready(function() {
api.routines.getRoutines().done(function(data) {
$.each(data, function(i, item){
var list = document.getElementById("routines_list");
var acc = document.createElement("div");
acc.setAttribute("class", "accordion");
var panel = document.createElement("div");
panel.setAttribute("class", "panel");
//more stuff
});
acc.appendChild(panel);
list.appendChild(acc);
// ...
});
addPanels(); //WORKS ONLY WITH PREVIOUS ACCORDIONS NOT WITH THE NEW ONE! WHY??

}).fail(function(jqXHR, textStatus, errorThrown) {
//do sth
});
});

addPanels 似乎只将监听器添加到不是从 API 加载的 ACCORDION 类元素(它们已经在 HTML 中)。为什么会这样?

最佳答案

因为在添加监听器时,您的新元素不存在。

api.routines.getRoutines().done 指定应在未来某个时间点运行的回调函数 - 我们不知道那会是什么时候。因此,当该 API 开始其流程时,接下来会立即调用 addPanels();,这会设置事件处理程序,但 getRoutines() 尚未完成然而,因此您最终只能在 getRoutines() 完成之前在面板上设置处理程序。这就是异步处理的工作原理。

要解决这样的问题,你需要使用 event delegation ,这是当你在一个从一开始就存在的对象上设置事件处理程序,然后你通过事件冒泡捕获由后代元素发起的事件。处理事件后,您检查事件的来源并查看它是否符合您想要的条件。这样,元素何时创建并不重要。

这是一个简化的例子:

// Set up a click event handler on the document (which all descendant element events will bubble up to)
document.addEventListener("click", function(evt){
console.log("Click event handled!");

// Is the clicked element NOT the document?
if(evt.target.classList){
// Check for dynamically created elements that were given
// the "dynamic" class upon creation (you can use any criteria you want here)
if(evt.target.classList.contains("dynamic")){
console.log("Click event for dynamically created element, " + evt.target.nodeName + " handled by document");
}
}
});

// Now, we'll create some elements and inject them into the DOM AFTER the event handler
// has been set up. Also, these elements were not specifically set up with event handlers.
var div = document.createElement("div");
div.classList.add("dynamic");
div.textContent = "Click Me";
document.body.appendChild(div);

var btn = document.createElement("input");
btn.classList.add("dynamic");
btn.type = "button";
btn.value = "Click Me!";
document.body.appendChild(btn);
.dynamic { font-weight:bold; color:#800080; }

关于javascript - 监听器未添加到创建的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310264/

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