动态地向列表中添加复选框和文本

Add a check box and text to an li dynamically

本文关键字:复选框 文本 添加 列表 动态      更新时间:2023-09-26

我正在尝试动态添加一个复选框和文本到一个li

我的代码

var statusList = document.createElement('ul');
for (var item in object) {
    var option = document.createElement('li');
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.name = "name";
    checkbox.value = "value";
    //these are the things I have tried. I can get the title or the checkbox 
      but not both
    //option.appendChild(checkbox); this adds the checkbox but not the text
    //option.appendChild(object[item]); this throws an error
    //option.text = checkbox + object[item]; this populates an empty li
    //option.innerHTML = checkbox + object[item]; this populates the 
    //checkbox but not as an element. in other words it will say 
    //[object HTMLInputElement] + text
    //option.text = object[item]; this populates the text but not checkbox
    option.value = item;
    statusList.appendChild(option);
}

请不要给出jquery的答案。只有javascript

从注释扩展:

Text节点也是一个节点,所以你可以像普通元素一样附加它:

option.appendChild(checkbox);
option.appendChild(document.createTextNode("TEXT")‌​);

MDN: document.createTextNode
MDN: Element.appendChild