我有以下代码的问题,for循环包含4个单击事件,我需要循环等待用户单击它们,然后继续迭代,但是当我运行代码时,它只是跳过侦听器。我在工厂函数中放置了console.log语句,看看发生了什么,我得到了这个:工厂运行01
//Array
let buttons = [];
let message = "Hi";
//creates a header with a questin and
let factory = (message, index) => {
let questionElement = document.createElement("h1");
console.log(`factory was run ${index}`);
//question holds a question that was send back
text = message;
//attaching text to questionElement
questionElement.append(text);
//return statement for header element
return questionElement;
};
let hi = (event) => {
console.log(`Hi from buttom ${event.data.button}`);
}
//Questions for loop
for (let i = 0; i < 2; i++) {
//Factory function creates a header for the question
let question = factory(message, i);
console.log(question)
//append question to the div container
$("#main-container").append(question);
//Loop that populates Buttons array
for (let l = 0; l < 4; l++) {
//Replaced JQuery with Vanilla
buttons[l] = document.getElementById("btn" + l);
}
//for loop that sets button's inner
//HTML's
for (let s = 0; s < buttons.length; s++) {
buttons[s].innerHTML = "Info";
}
//Button Listeners
$("#btn0").click(hi, {
button: "#btn0"
});
$("#btn1").click(hi, {
button: "#btn1"
});
$("#btn2").click(hi, {
button: "#btn2"
});
$("#btn3").click(hi, {
button: "#btn3"
});
}
您可以将此代码封装到一个async函数中(然后调用async函数,但在您的上下文中是适当的),这将允许您执行以下操作:
await new Promise((resolve, reject) => {
document.getElementById("btn0").addEventListner("click", (ev) => {
hi();
resolve();
}, { once: true });
})
如果您必须执行其中的四个,而不是复制上述代码四次并在每次代码中捕获hi
函数,您可以创建一个生产者辅助函数,如下所示:
function createClickPromise(btnId, hiCallback) {
return new Promise((resolve, reject) => {
document.getElementById("btn0").addEventListner("click", (ev) => {
hiCallback();
resolve();
}, { once: true });
});
}
await createClickPromise("btn0", hi);
await createClickPromise("btn1", hi);
await createClickPromise("btn2", hi);
await createClickPromise("btn3", hi);