我有一个如下所示的数组,它表示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");
}
}
做我正在做的事情的正确方法是什么?提前谢谢。
答案 0 :(得分: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");
}
}
}
答案 1 :(得分: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");
}