2015-08-25 66 views
2

我試圖不斷向所有輸入元素添加EventListener。Javascript - 事件在添加時觸發

但是,當我添加EventListener的功能被觸發。

window.onload = window.setInterval(function() { 
    var frame = document.getElementsByTagName("FRAME"); 
    for (var i = 0; i < frame.length; i++) { 
     frame_doc = frame[i].contentWindow.document || frame[i].contentDocument; 
     var elem = frame_doc.getElementsByTagName("INPUT"); 
     for (var j = 0; j < elem.length; j++) 
      if (elem[i]) { 
       alert(true); 
       //if(typeof elem[i].onclick === "function") 
       //removeEvent(elem[i], "click", check()); 
       addEvent(elem[i], "click", check()); 
      } 
    } 
}, 50); 

function addEvent(elem, event, fn) { 
    if (elem.addEventListener) { 
     elem.addEventListener(event, fn, false); 
    } else { 
     elem.attachEvent("on" + event, function() { 
      return (fn.call(elem, window.event)); 
     }); 
    } 
} 

function check() { 
    //Do Something 
} 

回答

3

因爲您在綁定新元素上的事件時調用該函數。 當綁定事件時使用check()時,函數check被調用。您可以刪除的check

addEvent(elem[i], "click", check()); 

()應該是

addEvent(elem[i], "click", check); // removed() of check