如何通过javascript动态添加选项?

时间:2013-07-30 22:22:40

标签: javascript

我试图在IE加载页面时通过JavaScript添加一个选项。我在谷歌搜索它,但仍然无法得到解决方案。

<html>
    <script type="text/javascript">
        function add(){
            var c = document.getElementById("number");
            var e = document.createElement("option");
            e.setAttribute("value", "1");
            e.appendChild(document.createTextNode("two");
            c.appendChild(e);
        }
    </script>
<body onload="add()">
    <form action="" method="post">
        favirate city:
        <select id="number">
            <option value="0">one</option>
        </select>
    </form>
</body>
</html> 

2 个答案:

答案 0 :(得分:0)

var option = new Option('myText', 'val');
var select = document.getElementById("number");
select.appendChild(option);

答案 1 :(得分:-1)

试试这段代码......我稍微更新了一下

<html>
    <script type="text/javascript">
        function add(){
            var c = document.getElementById("number");
            var lastVal = Number(c.lastChild.value) + 1;
            var e = document.createElement("option");
            e.setAttribute("value", lastVal);
            e.appendChild(document.createTextNode("two"));
            c.appendChild(e);
        }
    </script>
<body onload="add()">
    <form action="" method="post">
        favirate city:
        <select id="number">
            <option value="0">one</option>
        </select>
    </form>
</body>
</html>