javascript 使用javascript循环选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12257356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:43:26  来源:igfitidea点击:

for looping on the select options using javascript

javascriptfor-loop

提问by Kevin Steve Maningo

Here is my code:

这是我的代码:

<!doctype html>

<html>
<head>
    <meta charset="utf-8">
    <title>Date Picker</title>
</head>
<body>
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<select id="demo">
</select>
<p id="demo"></p>
<script>
function myFunction()
{
    var i;
    for (i=1;i<=5;i++){
      document.getElementById("demo").innerHTML="<option value="+i+">"+i+"</option>";
    }
}
</script>
</body>
</html>

all I want is when I press the button dropdown box will generate an option like this:

我想要的只是当我按下按钮时下拉框会生成一个这样的选项:

<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>

but I get only this code

但我只得到这个代码

<option value="5">5</option>

it only show 5 on the option. Please help.. Thank you

它只在选项上显示 5。请帮忙..谢谢

回答by KooiInc

You are overwriting the contents of 'demo' in every iteration. It's better to use DOM methods to add options to a select:

您在每次迭代中都覆盖了“演示”的内容。最好使用 DOM 方法向选择添加选项:

function myFunction(selector)
{
    var i;
    for (i=1;i<=5;i++){
      selector.options[i-1] = new Option(i,i);
    }
}
//usage:
myFunction(document.getElementById("demo"));

By the way: check your HTML. The idof elements should be unique. Using your HTML, how can your scripting know which element is meant with document.getElementById("demo")?

顺便说一句:检查您的 HTML。该id元素应该是唯一的。使用您的 HTML,您的脚本如何知道哪个元素与document.getElementById("demo")?

回答by Pranay Rana

Add element to select like this will work for you

像这样添加要选择的元素对您有用

var select = document.getElementById("demo");  

var i=0;
 for(i=1;i<=5;i++){  
     select.options[select.options.length] = new Option(i,i);  

}