2013-10-11 65 views
22

我試圖循環遍歷所有使用forEach從getElementsByTagName("input")重構的元素。任何想法爲什麼這不適用於FF,Chrome或IE?JavaScript:循環遍歷從getElementsByTagName返回的所有元素

<html> 
    <head> 
    </head> 
    <body> 
     <input type="text" value="" /> 
     <input type="text" value="" /> 
     <script> 
      function ShowResults(value, index, ar) { 
       alert(index); 
      } 
      var input = document.getElementsByTagName("input"); 
      alert(input.length); 
      input.forEach(ShowResults); 
    </script> 
    </body> 
</html> 
+0

理由爲什麼沒有'forEach':http://stackoverflow.com/questions/13433799/why-doesnt-nodelist-have-foreach –

回答

48

您需要的節點列表轉換爲數組與此:

<html> 
    <head> 
    </head> 
    <body> 
     <input type="text" value="" /> 
     <input type="text" value="" /> 
     <script> 
      function ShowResults(value, index, ar) { 
       alert(index); 
      } 
      var input = document.getElementsByTagName("input"); 
      var inputList = Array.prototype.slice.call(input); 
      alert(inputList.length); 
      inputList.forEach(ShowResults); 
    </script> 
    </body> 
</html> 

或使用循環。

for(i = 0;i < input.length; i++) 
{ 
    ShowResults(input[i].value); 
} 

,改變ShowResults功能是:

function ShowResults(value) { 
    alert(value); 
} 
+0

我試圖用這樣的:http://msdn.microsoft。 com/en-us/library/ie/ff679980%28v = vs.94%29.aspx – slayernoah

+0

請參閱我的編輯。 2個選項。 – Dvir

+0

我在表單上有> 1000個隱藏的輸入字段。在這種情況下哪個選項最有效? – slayernoah

4

這是becauseinput是HTML集合。 html集合沒有forEach。

,你可以很容易地通過Array.prototype.slice它CONVER數組

例如:

function ShowResults(value, index, ar) { 
      alert(index); 
     } 
     var input = document.getElementsByTagName("input"); 
     alert(input.length); 
input = Array.prototype.slice.call(input) 
     input.forEach(ShowResults); 

http://jsfiddle.net/fPuKt/1/

5

因爲input不是一個數組,這是HTMLCollection 使用for循環會會更好。

而且,由於HTMLCollection s爲陣列狀物體可以callArray#forEach上像這樣

Array.prototype.forEach.call(input, ShowResults); 
2

HTMLCollections不具有相同的方法數組。您可以通過在瀏覽器的JavaScript控制檯中進行提示來檢查此問題。

var elements = document.getElementsByClassName('some-class'); 
'forEach' in elements; 

,控制檯將返回true如果elements(在這種情況下)有一個名爲forEach調用方法。

3

究其原因,這是行不通的,因爲 '的getElementsByTagName' 返回數組 - 像對象,而不是實際數組。如果你不知道,這裏是如何他們兩個看起來像: -

var realArray = ['a', 'b', 'c']; 
var arrayLike = { 
    0: 'a', 
    1: 'b', 
    2: 'c', 
    length: 3 
}; 

因此,由於陣列狀物體從「Object.prototype中」而不是「Array.prototype」繼承,這意味着類似於數組的對象無法像forEach(),push(),map(),filter()和slice()那樣訪問常見的數組原型方法。

希望有幫助!

+0

這是一個很好的解釋 – Dvir

0

我這樣做:

HTMLCollection.prototype.map = Array.prototype.map; 

您現在可以使用地圖上的每個HTMLCollection

document.getElementsByTagName("input").map(
    input => console.log(input) 
);