2011-10-12 79 views
1

我有一個數組如下所示其代表在HTML體的主體的對象的id:訪問數據動態

var p=new Array ("p1" ,"p2" ,"p3" ,"p4" ,"p5","p6","p7","p8","p9","p10","p11" ,"p12","p13", "p14","p15","p16","p17","p18","p19","p20"); 

我需要遍歷這些對象和檢索自己的數據,我就是在這種不正常的方式如下這樣:

for(var i=0; i<20; i++) 
     { 
      var price=p[i].innerHTML; 
      if(price.length != 7) 
      { 
      alert("yes"); 
      } 
     } 

是什麼做什麼,我試圖做正確的方法是什麼?提前致謝。

回答

2

您需要getElementById()

for(var i=0; i<20; i++) 
{ 
    var price = document.getElementByid(p[i]).innerHTML; 
    if(price.length != 7) 
    { 
    alert("yes"); 
    } 
} 

訪問節點要謹慎一點,可以先驗證節點存在:

for(var i=0; i<20; i++) 
{ 
    var elem = document.getElementByid(p[i]); 
    // Only attempt to do anything if the node exists... 
    if (elem) 
    { 
    var price = elem.innerHTML; 
    if(price.length != 7) 
    { 
     alert("yes"); 
    } 
    } 
} 
0
var p=new Array ("p1" ,"p2" ,"p3" ,"p4" ,"p5","p6","p7","p8","p9","p10","p11" ,"p12","p13", "p14","p15","p16","p17","p18","p19","p20"); 

for (var i = 0, var element = document.getElementById(p[i]); i < p.length; i ++) { 
    var price = ""; 
    if (element) price = element.innerHTML; 
    if (price.length != 7) alert("yes"); 
}