javascript - javascript 中的动态复选框列表 - 不起作用

标签 javascript html checkbox innerhtml

当从下拉列表中选择某个元素时,我试图创建一个复选框列表。但是,在下面的代码中,我只获得了复选框列表中的最后一个元素。也就是说,在输出中,没有 3 个复选框(我的数组的长度),但只有一个 - 只有数组中的最后一个元素。

我做错了什么?

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>


    <script>
     function chooseTable(db) {


 if(db=="hr.employee"){

var div = document.getElementById("table"); 

var ids = ["id","name", "write_uid"];

var main = document.getElementById('main1');

var parentElement = document.getElementById('ids');

for(var count in ids)
{
    var newCheckBox = document.createElement('input');
    newCheckBox.type = 'checkbox';
    newCheckBox.id = 'id' + count; // need unique Ids!
    parentElement.innerHTML = ids[count];
    newCheckBox.value = ids[count];
    parentElement.appendChild(newCheckBox);

}

 }
 }


 </script>
  <center>
    <bold>
    <h2>
    Make Query
    </h2>
    </bold>

<div id="main1">
<div>

Choose database:<br/>

<select id="table" name="table" onchange="chooseTable(this.value)">

     <option name="choice" value=""></option>
    <option name="choice1" value="hr.employee">Employees</option>
    <option name="choice2" value="account.account">Accounts</option>
  </select>
</div>  

<div id="ids">

</div>
</div>

</center>

  </body>
</html>

最佳答案

问题是 parentElement.innerHTML = ids[count]; 代码。它清除所有以前的 html 内容。并且要将标签添加到复选框,最好使用标签标签。试试这个:

for(var count in ids)
{
    var newCheckBox = document.createElement('input');
    newCheckBox.type = 'checkbox';
    newCheckBox.id = 'id' + count; // need unique Ids!
    newCheckBox.value = ids[count];
    parentElement.appendChild(newCheckBox);
    var newLabel = document.createElement('label');
    newLabel.innerHTML = ids[count];
    parentElement.appendChild(newLabel);

}

关于javascript - javascript 中的动态复选框列表 - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009712/

相关文章:

javascript - 如何将节点内容从 xml 复制到硬编码的 html(动态到原始 html)?

javascript - Bxslider 图像在我刷新页面之前未加载?

javascript - 如何在javascript中更改列表标签的 float 样式?

javascript - MathJax 公式之间的右光标位置

javascript - knockout 中复选框列表的选中属性

javascript - 是否可以允许人们将我的 Youtube channel 上的视频上传到我的网站在 asp.net 中进行身份验证

Firefox 3.6.13 中的 Javascript 参数

javascript - 如何在html5中不重叠地随机生成圆圈?

javascript - 当复选框被选中/取消选中时触发函数?

javascript - 从 javascript 调用 OnCheckedChanged 事件