0

我正在尝试将复选框和文本动态添加到 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

4

1 回答 1

1

从评论扩展:

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

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

MDN:document.createTextNode
MDN:Element.appendChild

于 2013-06-07T03:12:32.653 回答