JavaScript的:遍历所有元素的getElementsByTagName从返回 [英] JavaScript: Loop through all the elements returned from getElementsByTagName

查看:470
本文介绍了JavaScript的:遍历所有元素的getElementsByTagName从返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从通过 retruned的所有元素的getElementsByTagName(输入),试图循环使用的forEach。任何想法,为什么这并不在FF,Chrome或IE浏览器?

I am trying to loop through all the elements retruned from getElementsByTagName("input") using forEach. Any ideas why this does not work in FF, Chrome or IE?

<html>
    <head>
    </head>
    <body>
        <input type="text" value="" />
        <input type="text" value="" />
        <script>
            function ShowResults(value, index, ar) {
                alert(index);
            }
            var input = document.getElementsByTagName("input");
            alert(input.length);
            input.forEach(ShowResults);
    </script>
    </body>
</html>

感谢您的时间!

推荐答案

您需要的节点列表转换为数组这样的:

You need to convert the nodelist to array with this:

<html>
    <head>
    </head>
    <body>
        <input type="text" value="" />
        <input type="text" value="" />
        <script>
            function ShowResults(value, index, ar) {
                alert(index);
            }
            var input = document.getElementsByTagName("input");
            var inputList = Array.prototype.slice.call(input);
            alert(inputList.length);
            inputList.forEach(ShowResults);
    </script>
    </body>
</html>

或使用循环。

for(i = 0;i < input.length; i++)
{
    ShowResults(input[i].value);
}

和改变ShowResults功能是:

and change ShowResults function to:

function ShowResults(value) {
   alert(value);
}

这篇关于JavaScript的:遍历所有元素的getElementsByTagName从返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆