循环使用JavaScript的选择选项 [英] for looping on the select options using javascript

查看:109
本文介绍了循环使用JavaScript的选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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>

但是我只得到这个代码

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

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

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

推荐答案

您在每次迭代中都覆盖demo的内容。使用DOM方法向select中添加选项会更好:

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

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

顺便说一下:检查您的HTML。元素的 id 应该是唯一的。使用你的HTML,你的脚本怎么知道哪个元素是用 document.getElementById(demo)

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

这篇关于循环使用JavaScript的选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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