[英]Javascript - How to add 0 to 10 options to select element?
I am struggling to understand to why my code only creates this single option:我很难理解为什么我的代码只创建了这个单一选项:
And not options from 0 to 10?而不是从 0 到 10 的选项?
<div> <div id="SelectEl"> </div> </div> <script> // Get el ID var el = document.getElementById('SelectEl'); // Select element var selectList = document.createElement('select'); // Option element var option = document.createElement('option'); for (var i = 0; i < 11; i++) { // Add selectList element to div el.appendChild(selectList); // Add option to selectList selectList.appendChild(option); // Add text of a number 0 to 10 option.text = [i] } </script>
<div> <div id="SelectEl"> </div> </div> <script> // Get el ID var el = document.getElementById('SelectEl'); // Select element var selectList = document.createElement('select'); // Option element var option; for(var i = 0; i < 11; i++) { option = document.createElement('option'); // Add text of a number 0 to 10 option.text = [i] // Add option to selectList selectList.appendChild(option); } // Add selectList element to div el.appendChild(selectList); </script>
Create the option element inside the loop, one for each iteration, and move the line where you append the selectList to the div to outside the loop:在循环内创建 option 元素,每次迭代一个,并将将 selectList 附加到 div 的行移动到循环外:
const el = document.getElementById('SelectEl'); const selectList = document.createElement('select'); el.appendChild(selectList); for (var i = 0; i < 11; i++) { var option = document.createElement('option'); selectList.appendChild(option); option.text = [i] }
<div id="SelectEl"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.