javascript 中没有重复

no repeat in javascript

你好,我是 javascript 的新人,很抱歉回答这个初级问题, 所以我想对许多按钮执行相同的操作很容易我想在单击它时激活按钮所以有我的代码:

var button = document.querySelector(".button_cadre_work");
 
   button.addEventListener("click", function(e) {
      this.classList.toggle("is-active"); 
  });
  
  var button = document.querySelector(".over_btn");
 
   button.addEventListener("click", function(e) {
      this.classList.toggle("is-active"); 
  });
  
  var button = document.querySelector(".button_cadre_about");
 
   button.addEventListener("click", function(e) {
      this.classList.toggle("is-active"); 
  });

我如何优化它以防止每次重复

var buttons = document.querySelectorAll('.button_cadre_work, .over_btn, .button_cadre_about');
var buttonClickHandler = function(e) {
  this.classList.toggle("is-active"); 
};
// EITHER
Array.prototype.forEach.call(buttons, function(button) {
  button.addEventListener('click', buttonClickHandler);
});
// OR
for (var i = 0; i < buttons.length; i++) {
  var button = buttons[i];
  button.addEventListener('click', buttonClickHandler);
}
var buttonClickHandler = function(e) {
  this.classList.toggle("is-active"); 
};
NodeList.prototype.forEach = Array.prototype.forEach; //this will allow you to do this in other similar situations
var buttons = document.querySelectorAll('.button_cadre_work, .over_btn, .button_cadre_about').forEach(function(el) {
  el.addEventListener('click', buttonClickHandler);
})

您可以在所有元素上放置相同的 class 并循环遍历它们。我正在使用 while 循环而不是 array forEach 循环。

function loops(items, fn, onLoopComplete) {
  var i;
  try {
    if (items && items.length) {
      i = items.length;
    } else {
      throw new Error(items + ' is required to have a length');
    }

    if (i > -1) {
      do {
        if (items[i] !== undefined) {
          fn(i);
          /* console.log(i + ' is the current iteration'); */
        }
      }
      while (--i >= 0);
    }
    if (typeof onLoopComplete === 'function') {
      onLoopComplete(items.length);
    }
  } catch (e) {
    throw new Error(e);
  }
}

var button = document.querySelectorAll(".buttons");

loops(button, function(i) {
  button[i].addEventListener("click", function(e) {
    alert(button[i].className);
    button[i].classList.toggle("is-active");
  });
});
<li class="buttons button_cadre_work">one</li>
<li class="buttons over_btn">two</li>
<li class="buttons button_cadre_about">three</li>