簡體   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