javascript

时间:2015-05-25 04:10:13

标签: javascript jquery repeat

您好我是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"); 
		});




如何优化它以避免重复evrytime

3 个答案:

答案 0 :(得分:1)

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);
}

答案 1 :(得分:1)

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);
})

答案 2 :(得分:1)

您可以在所有元素上放置相同的类,并通过它们循环。我正在使用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>