如何使用javascript用按钮填充表单列表

How to populate a form list with buttons using javascript

本文关键字:填充 表单 列表 按钮 何使用 javascript      更新时间:2023-09-26

>我做了一个脚本,当你按下一个按钮(accessories)时,选择(mylist)填充一个数组(accessoryData),当你点击另一个按钮(weapons)时,另一个数组(weaponData)填充选择。但是,在代码的当前状态下,按下第二个按钮不会重新填充所选内容。这是怎么回事?

此外,如果有更有效的方法可以做到这一点,那可能会有所帮助。

完整代码

function runList(form, test) {
    var html = "";
    var x;
    dataType(test);
    while (x < dataType.length) {
        html += "<option>" + dataType[x];
        x++;
    }
    document.getElementById("mylist").innerHTML = html;
}

我相信您正在尝试制作一个<select>元素,即下拉菜单,但正确的标记是:

<select id="myList">
   <option value="1">Option 1</option>
   <option value="2">Option 2</option>
   <option value="n">Option n</option>
</select>

您忘记使用innerHTML属性关闭<option>标记。

使用本机 JS 方法:

//create the select element
var select = document.create('select');
//or use getElementById if it's already there
//Assuming your datatype is an Array of string
var opt;
for(var i=0; i<datatype.length; i++){
  //create the option element
  opt = document.create('option');
  opt.textContent = datatype[i]; //innerText works too
  //set the value attribute
  opt.setAttribute('value',i+1); //+1 or else it would start from 0
  //add the option to the select element
  select.appendChild(opt);
  //conversely use removeChild to remove
}
//at last add it to the DOM if you didn't fetch it from the DOM.