如何使用javascript从数组中获取每个值

时间:2021-11-13 01:02:37

I am displaying 2 values from database inside <h1> tag. there more tags in my page.

我在

标签内的数据库中显示2个值。我的页面中有更多标签。

<?php
foreach($arrays as $row)
{
?>
<h1 id="myId"><?php echo  $row['field_name'];?></h1>
<?php
}

I want each values for checking. How will I get using JavaScript?. only two values will get inside <h1> tag.

我想要每个值进行检查。我将如何使用JavaScript?只有两个值会进入

标记内。

please help.

3 个解决方案

#1


0  

Change the id to class and then you will get the desired result.

将id更改为class,然后您将获得所需的结果。

#2


0  

Use below javascript to fetch all values inside h1 tag.

使用下面的javascript来获取h1标记内的所有值。

var h1Elements = document.getElementsByTagName("h1");
for(var i = 0; i < h1Elements.length; i++)
{
    alert(h1Elements[i].innerHTML);
}

Note:- Id must be unique in DOM. You should use Class if it is in loop.

注意: - Id在DOM中必须是唯一的。如果它在循环中,你应该使用Class。

#3


0  

ids must be unique. Use a class in the php:

ID必须是唯一的。在php中使用一个类:

<h1 class="my-class"><?php echo  $row['field_name'];?></h1>

Then call document.getElementsByClassName("my-class") in your javascript, and iterate over the results:

然后在你的javascript中调用document.getElementsByClassName(“my-class”),并迭代结果:

var els = document.getElementsByClassName("my-class");
for(var i = 0; i < els.length; ++i) alert(els[i].innerHTML);

#1


0  

Change the id to class and then you will get the desired result.

将id更改为class,然后您将获得所需的结果。

#2


0  

Use below javascript to fetch all values inside h1 tag.

使用下面的javascript来获取h1标记内的所有值。

var h1Elements = document.getElementsByTagName("h1");
for(var i = 0; i < h1Elements.length; i++)
{
    alert(h1Elements[i].innerHTML);
}

Note:- Id must be unique in DOM. You should use Class if it is in loop.

注意: - Id在DOM中必须是唯一的。如果它在循环中,你应该使用Class。

#3


0  

ids must be unique. Use a class in the php:

ID必须是唯一的。在php中使用一个类:

<h1 class="my-class"><?php echo  $row['field_name'];?></h1>

Then call document.getElementsByClassName("my-class") in your javascript, and iterate over the results:

然后在你的javascript中调用document.getElementsByClassName(“my-class”),并迭代结果:

var els = document.getElementsByClassName("my-class");
for(var i = 0; i < els.length; ++i) alert(els[i].innerHTML);