跨浏览器附加功能 javascript

Cross-browser addevent function javascript

我正在尝试创建一个函数,为 class 中的每个按钮添加一个事件。我将所有按钮都放在一个数组中并想使用 Dustin Diaz's addevent() cross browser solution,但不确定如何实现它。我习惯于为这类事情使用框架,但必须为此使用纯 JS。 任何关于如何使用 Dustin 的解决方案的指示或建议将不胜感激。

好的,所以在听取了@Pointy 的建议后,我写了这篇文章来检查 addEventListener,如果没有则使用 attachEvent 然而,这并没有调用 testFunction()。我在这里做错了什么?

function addEvents()
{
  var buttonArray=document.getElementsByClassName('mainButton');

  for(i=0; i < buttonArray.length; i++)
  {
    if (i.addEventListener) {
      i.addEventListener("click", testFunction);
    } 
    else if (i.attachEvent) {
      i.attachEvent("onclick", testFunction);
    }

    function testFunction() {
      alert("Test");
    } 
  }

  // Attach an event to each button that when clicked on will display an alert that say 'Button X clicked' where X = the button ID
}

您正在尝试向号码添加事件。您应该将 "i" 替换为 "buttonArray[i]" 并添加一个 else-case(防御性编码)。

function addEvents() {
    var buttonArray = document.getElementsByClassName('mainButton');
    for(i = 0; i < buttonArray.length; i++) {    
        if (buttonArray[i].addEventListener) {
            buttonArray[i].addEventListener("click", testFunction);
        } else if (buttonArray[i].attachEvent) {
            buttonArray[i].attachEvent("onclick", testFunction);
        } else {
            throw new Error("This should be unreachable");
        }
    }

    function testFunction() {
        alert("Test");
    }
}