javascript - 使用 JavaScript 填充 <select>

标签 javascript html forms

所以我想在我的表单中添加一个下拉列表,它将显示从 1 到 999 的数字。 我尝试过使用 JS 来实现,但没有成功 这是我到目前为止所尝试过的:

<html>
<head>
<script>
window.onload = fillDropDown(); 

function fillDropDown() { 
var ddl = document.getElementById( 'myDropdown' ); 
var theOption = new Option; 
var x; 
var i; 

for(i = 0; i < 999; i++) { 
x = i + 1; 
theOption.text = x; 
theOption.value = x; 
ddl.options[i] = theOption; 
} 
} 
</script>
</head>
<body>
<form id="myForm"> 
<select id="myDropdown"></select> 
</form>
</body>

但是这不起作用。 这是一个 jsfiddle 示例 http://jsfiddle.net/j3nLxptn/

最佳答案

如果您在循环内实例化该选项,它就会起作用:

 for (i = 0; i < 999; i++) {
        var theOption = new Option;
        x = i + 1;
        theOption.text = x;
        theOption.value = x;
        ddl.options[i] = theOption;
    }

参见http://jsfiddle.net/j3nLxptn/1/

关于javascript - 使用 JavaScript 填充 <select>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477389/

相关文章:

javascript - 在liferay中为aui窗体添加动态元素

javascript - 检查 Handsontable 中的空属性

javascript - 如何在 Bootstrap Tour 中跳过 10 个步骤?

html - CSS 下拉菜单对齐不起作用

javascript - 如何在 jquery 中创建垂直滚动的 div?

javascript - 如何在HTML中触发onChange事件,即使在js中内容发生了变化?

javascript - 从 JSON 值实现计数器

javascript - 影响多个相同元素并避免不在 DOM 中时发生 null 错误,纯 JavaScript 与 jQuery

javascript - 文本输入 - 限制小数点后不超过 5 位且数字超过 100

html - 如何更改 &lt;input type = "submit"> 的高度