这是我的代码
for(var i=0;i<Year12.length;i++)
{
var div1=document.createElement('li');
div1.setAttribute('id',Year12[i]);
div1.setAttribute('Value',Year12[i]);
document.getElementById("Jan").appendChild(div1);
alert(div1);
}
“jan”是 UL 元素的 id。我能够创建该元素。但它没有添加到父元素。任何人都可以尝试这个
最佳答案
删除值并尝试:
var div1=document.createElement('li');
div1.setAttribute('id',Year12[i]);
div1.innerHTML= Year12[i];
document.getElementById("Jan").appendChild(div1);
alert(div1);
或者
var div1=document.createElement('li');
div1.setAttribute('id',Year12[i]);
div1.appendChild(document.createTextNode(Year12[i]));
document.getElementById("Jan").appendChild(div1);
alert(div1);
要设置类别,您可以执行以下操作:
div1.className = "your_class_name";
关于JavaScript 附加子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11825811/