开发者

Access data of objects through IDs dynamically

I have an array as shown below which represents the ids of objects in the body of the HTML body:

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

i need to iterate over those objects and retrieve their data, and i'm doing this in the following way which is not working:

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

What is the correct way to do what i'm trying to do? Thanks in advance.


You need to access the nodes with getElementById()

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

To be a little more cautious, you can first verify that the node exists:

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");
     }
  }
}


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜