繁体   English   中英

跨浏览器的addevent函数javascript

[英]Cross-browser addevent function javascript

我正在尝试创建一个将事件添加到类中每个按钮的函数。 我将所有按钮都放在一个数组中,并想使用Dustin Diaz的addevent()跨浏览器解决方案 ,但不确定如何实现它。 我已经习惯使用框架来完成这种事情,但是必须使用纯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]”,并添加其他情况(防御性编码)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM