Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

javascript - JavaScript - 使用数组填充下拉列表(JavaScript - populate drop down list with array)

I have an array declared in a script:(我在脚本中声明了一个数组:)

var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N"); I have a form which contains a drop down menu:(我有一个包含下拉菜单的表单:) <form id="myForm"> <select id="selectNumber"> <option>Choose a number</option> </select> </form> Using Javascript, how will I populate the rest of the drop down menu with the array values?(使用Javascript,我将如何使用数组值填充下拉菜单的其余部分?) So that the options will be "Choose a number", "1", "2", "3", "4", "5" .(这样选项将是“选择一个数字”,“1”,“2”,“3”,“4”,“5”。) .(。) .(。) .(。) .(。) "N"?(“N”?)   ask by user1296265 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to loop through your array elements, create a new DOM node for each and append it to your object.(您需要遍历数组元素,为每个元素创建一个新的DOM节点并将其附加到您的对象。)

var select = document.getElementById("selectNumber"); var options = ["1", "2", "3", "4", "5"]; for(var i = 0; i < options.length; i++) { var opt = options[i]; var el = document.createElement("option"); el.textContent = opt; el.value = opt; select.appendChild(el); }? Live example(实例)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...