繁体   English   中英

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

[英]How to populate a form list with buttons using javascript

我做了一个脚本,当您按下一个按钮( 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM