首页 > 解决方案 > 如何从 document.querySelectorAll() 正确循环遍历 NodeList?

问题描述

在学习不同 AJAX 请求的练习中,我想在#quote每次单击按钮时应用淡入淡出转换。(渐变效果不是练习的一部分,只是我自己添加的)

密码笔

我知道当有一个按钮(或只有第一个按钮)时如何执行此操作document.querySelector(),但我了解到它document.querySelectorAll()以数组的形式返回一个静态 NodeList,您将需要遍历数组以对每个按钮执行某些操作。

我已经尝试了几件事,但我无法弄清楚。

这就是我到目前为止所拥有的,据我所知,这 2 位代码需要在彼此内部,我的问题是如何.

// Quote animation
var buttons = document.querySelectorAll("button");

[].forEach.call(buttons, function(button){
  // quote should have .fade applied every time one of the four buttons is clicked
});

$(button).addEventListener("click", function(){
    $(quote).addClass("fade");
    $(quote).bind('oanimationend animationend webkitAnimationEnd', function(){ 
        $(this).removeClass("fade");
    });
})

标签: javascriptjquerycssdom

解决方案


这将选择每个按钮并触发您的淡入淡出效果

$("button").on('click', function(){
    $(quote).addClass("fade");
    $(quote).bind('oanimationend animationend webkitAnimationEnd', function(){ 
        $(this).removeClass("fade");
    });
});

推荐阅读