用于向页面添加按钮的JavaScript代码

时间:2013-08-18 08:29:29

标签: javascript

我有这个非常简单的代码:

<body onload="OnLoad()">
    <script>
        function OnLoad() {

        for (i = 0 i < 3; ++i)
        {
                var name = 'Test' + i;
                var menuBtn = document.createElement('input');
                menuBtn.setAttribute('type', 'button');
                menuBtn.setAttribute('value', name);
                menuBtn.setAttribute('name', name);
                menuBtn.setAttribute('id', name);
                document.body.appendChild(menuBtn);
            }

        }
    </script>
</body>

你可以在这里看到它:JSFiddle如果我删除for循环它可以正常工作。这段代码有什么问题?

3 个答案:

答案 0 :(得分:7)

你的for循环中缺少一个SemiColon:

for (i = 0; i < 3; ++i)

它应该解决问题

答案 1 :(得分:2)

您的错误在于(i = 0 i < 3; ++i)

改为使用此

(var i = 0; i < 3; ++i)

答案 2 :(得分:1)

您在i = 0

之后忘记了for循环中的分号
for (i = 0; i < 3; ++i)