2017-04-25 84 views
0

我的目标是让appendChild(detail)出现在appendChild(image)之后,但它不会显示在浏览器中。我需要在dom div中添加第三个appendchild()

document.getElementById("myBtn2").addEventListener("click", hey); 

function hey(){  
    for (i = 1; i < radio.length; i++){ 
     f = radio[i].image ; 

     var item = document.createElement('div'); 
     item.id = "box"; 
     item.className = "dell"; 
     item.style.height = "140px"; 
     detail = document.createElement('div'); 
     detail.className = "space"; 
     image = document.createElement('img'); 
     image.id = "pic"; 
     image.className = "dell3"; 
     image.setAttribute("src", f); 

     document.getElementById('case').appendChild(item).appendChild(image).appendChild(detail);         
    } 
} 
+0

让我们看看你的HTML吧 –

回答

0

appendChild()返回附加节点。它不是可链接的您认为的方式。在您的代码中,item附加到'case',imageitemdetailimage。由于image是不应该有子女的<img>元素,因此不会显示detail

解决方法是将每个项目分别追加到文档片段,然后将文档碎片附加到案例。

var frag = document.createDocumentFragment(); 
var item = frag.appendChild(document.createElement('div')); 
item.id = "box"; 
item.className = "dell"; 
item.style.height = "140px"; 
var detail = frag.appendChild(document.createElement('div')); 
detail.className = "space"; 
var image = frag.appendChild(document.createElement('img')); 
image.id = "pic"; 
image.className = "dell3"; 
image.setAttribute("src", f); 

document.getElementById('case').appendChild(frag); 

注意你可能要在其他变量赋值VAR关键字太否则你将创建为每一个隐含的全局变量。我已经将这些添加到了我所做的示例更改中。还有其他的优化可能也需要做,比如每次循环时都不要执行document.getElementById()查找(可以将它作为var存储在循环之外)。

+0

不错。现在它更有意义。 – BERRY