问题描述
我正在尝试创建一个动态选项列表,我有一个包含我想要的数据的数组。我的想法是做一个 for,给它数组的长度并在里面创建选项,但这样做时它对我不起作用,它只会创建一个选项。
addEventListener('load',inicio,false);
function inicio(){
var dato = document.getElementById("dato1").value;
var boton = document.getElementById("b_enviar");
var b_a = document.getElementById("b_crear");
var datos = new Array();
boton.addEventListener('click',function(){
datos.push(document.getElementById("dato1").value);
console.log(datos);
},false);
b_crear.addEventListener('click',function(){
var section1 = document.getElementById('section1');
var section2 = document.getElementById('section2');
var select = document.createElement('select');
var option = document.createElement('option');
var s1 = section1.appendChild(select);
for (let index = 0; index < datos.length; index++) {
s1.appendChild(option);
console.log(index);
}
},false);
}
解决方法
-
s1.appendChild(option);一遍又一遍地附加相同的选项。将 for 循环线移至选项创建上方,并向您的选项添加文本和值
-
你想在追加之前清除选择或带有选择的容器 - 否则每次点击都会一遍又一遍地追加数组,使选择越来越长,重复数据
-
var s1 = 不是必需的。您已经有了可以用来附加到的 var select
-
你有
var b_a = document.getElementById("b_crear");
但没有使用它
所以把所有的问题加在一起,我们得到了这样的东西
forEach 更容易阅读
function inicio() {
var dato = document.getElementById('dato1').value;
var boton = document.getElementById("b_enviar");
var b_a = document.getElementById('b_crear');
var datos = [];
boton.addEventListener('click',function() {
const val = document.getElementById('dato1').value;
if (!datos.includes(val)) datos.push(val);
});
b_a.addEventListener('click',function() {
const section1 = document.getElementById('section1');
section1.innerHTML="";
const select = document.createElement('select');
let option = document.createElement('option');
option.value = "";
option.textContent = "Please select";
select.appendChild(option);
datos.forEach((dato,index) => {
option = document.createElement('option');
option.value = dato;
option.textContent = dato;
select.appendChild(option);
});
section1.appendChild(select)
})
}
window.addEventListener('load',inicio);
<input type="text" id="dato1">
<button id="b_enviar">Enviar</button>
<button id="b_crear">Crear</button>
<div id="section1"></div>