如何在Jquery中为数组的每个元素添加持续时间



我必须使用此js代码通过从单击的按钮中获取值来添加数组。因此,我将它们存储在一个数组中,以将其传递到函数中,该函数将添加到我的主HTML中。我面临的问题是,它会被我单击的每个按钮添加到数组中,但它不会给每个元素执行时间。它直接显示了最后一个元素的效果。

// We create a Promise and return it
new Promise((resolve, reject) => {
const animationName = `${animation}`;
const node = document.querySelector(element);
node.classList.add(`${prefix}animated`, animationName);
// When the animation ends, we clean the classes and resolve the Promise
function handleAnimationEnd(event) {
event.stopPropagation();
node.classList.remove(`${prefix}animated`, animationName);
resolve("Animation ended");
}
node.addEventListener("animationend", handleAnimationEnd, { once: true });
});
var arrayOfButtonId = [];
var counter = 1;
$(".buttons-container").click(function (e) {
var clickedItemId = e.target.id;
//   var clickedItemValue = e.target.value;
arrayOfButtonId.push(clickedItemId);
arrayOfButtonId.forEach((index) => {
console.log(index);
animateCSS(".sample-display", index).then(() => {
alert(" animation created successfully!");
});
});
});

这是我试图实现的代码。

超级经典的问题,您不能期望像Promise这样的异步机制(即使使用await,更不用说使用.then()(在同步数组方法(forEach、map、filter等(中工作,如这里所解释的。

您需要forasync/await:

$(".buttons-container").click( async function (e) {
var clickedItemId = e.target.id;
arrayOfButtonId.push(clickedItemId);

for( let index in arrayOfButtonId){
console.log(index);
await animateCSS(".sample-display", index);
console.log("animation created successfully!");
}    
});

另外,去掉alert(),因为它阻塞了用户界面,有点违背了异步的目的。请改用console.log

最新更新