2012-05-11 27 views
-1

我確定我錯過了一些明顯的,但任何想法爲什麼下面的addEventListener代碼到處發射(不只是在提交按鈕)?JavaScript的addEventListener射擊所有元素

HTML:

<form action="#"> 
     <input type="text"><br> 
     <input type="text"><br> 
     <button id="submit">submit</button><br> 
    </form> 

JS:

function validate() { 
     var inputs = document.getElementsByTagName('input'); 
     var inputs_length = inputs.length-1; 
     for (i=0; i<=inputs_length; i++) { 
      var inputs_value = document.getElementsByTagName('input')[i].value; 
      if (inputs_value == "") { 
       alert('there is a text box empty'); 
      } 
     } 

    } 

    var el = document.getElementById('submit'); 

    if (el.addEventListener) { 
     el = addEventListener('click', validate, false); 
    } else if (el.attachEvent) { 
     el.attachEvent('onclick', validate); 
    } 

解決方法是CHANGE

el = addEventListener('click', validate, false); 

TO

el.addEventListener('click', validate, false); 

MY TYPO :(

回答

1

更改此:

if (el.addEventListener) { 
    el = addEventListener('click', validate, false); 

要這樣:

if (el.addEventListener) { 
    el.addEventListener('click', validate, false); 
+0

Doh !.明顯。 Ta :) – Adi

0

一個冗長的評論。

在您的代碼:

// inputs is an HTMLCollection of all the inputs 
    var inputs = document.getElementsByTagName('input'); 

    // No need for the -1 
    var inputs_length = inputs.length; 

    // Don't forget to declare counters too, very important 
    // Just use < length 
    for (var i=0; i<inputs_length; i++) { 

     // Instead of this very inefficient method 
     var inputs_value = document.getElementsByTagName('input')[i].value; 

     // use the collection you already have 
     var inputs_value = inputs[i].value; 

     if (inputs_value == "") { 
      alert('there is a text box empty'); 
     } 
    } 

而且最好在開頭聲明inputs_value所以所有聲明都在一個地方,但你擁有它是無害的。

哦,並且不要給表單元素一個「submit」(或任何其他表單方法)的名稱或ID,因爲它會影響同名的表單方法,所以無法調用。

+0

很酷。爲提示RobG歡呼 – Adi

相關問題