gpt4 book ai didi

javascript - 通过ID动态访问对象数据

转载 作者:行者123 更新时间:2023-11-30 18:37:50 24 4
gpt4 key购买 nike

我有一个如下所示的数组,它表示 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");
}
}

做我想做的事情的正确方法是什么?提前致谢。

最佳答案

您需要使用 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");
}
}
}

关于javascript - 通过ID动态访问对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7745028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com