【问题标题】:How to append multiple child div nodes如何追加多个子div节点
【发布时间】:2019-03-16 00:28:34
【问题描述】:

我正在使用从 codepen 获得的这段代码将 div 节点附加到父 div 并且它工作正常。

var el = document.getElementById('items'),

elChild = document.createElement("div");

elChild.innerHTML = '<div class="product"><a href="product1.html"><img  src="images/product1.png" alt="product1" /></a></div>'

el.appendChild(elChild);

如何添加更多 div 元素,因为我尝试按照下面的代码添加它们但失败了,提前致谢

var el = document.getElementById('items'),

elChild = document.createElement("div");

elChild.innerHTML = '<div class="product"><a href="product1.html"><img   src="images/product1.png" alt="product1" /></a></div>'
                    '<div class="product"><a href="product2.html"><img src="images/product2.png" alt="product2" /></a></div>'
                    '<div class="product"><a href="product3.html"><img src="images/product3.png" alt="product3" /></a></div>'


el.appendChild(elChild);

【问题讨论】:

标签: javascript append


【解决方案1】:

这似乎是一个简单的语法错误:

elChild.innerHTML = '<div class="product"><a href="product1.html"><img  src="images/product1.png" alt="product1" /></a></div> <div class="product"><a href="product2.html"><img src="images/product2.png" alt="product2" /></a></div><div class="product"><a href="product3.html"><img src="images/product3.png" alt="product3" /></a></div>' 

内部 html 接收一整串文本,而不是您发布的 3 个单独的字符串。

此外,如果您在 innerHTML 中动态创建 div 可能会更好,因为它们遵循清晰的模式:

var nProducts = 3, out="";
for(var i=1; i<=nProducts; i++){
    out+= '<div class="product"><a href="product'+i+'.html"><img src="images/product'+i+'.png" alt="product'+i+' " /></a></div>';
}
elChild.innerHTML = out;

此代码应在您想要的 div 中为 n 产品创建结构。

根据您的要求进行编辑: (虽然您应该自己学习如何做,但 w3schools 是一个不错的起点)

var products = ["phones", "computers", "whatever-other-product"]; //Create an array of your product names
var out="";
for(var i=0; i<products.length; i++){ //loop through the products array
    out+= '<div class="product"><a href="'+products [i]+'.html"><img src="images/'+product[i]+'.png" alt=" '+product[i]+' " /></a></div>';
}
elChild.innerHTML = out;

【讨论】:

  • 非常感谢,我以product1、product2和product3为例,如何将它们替换为phones.HTML、computers.HTML、cameras。 HTML
  • 尝试使用数组来存储值
  • @Stephen 查看我编辑的答案。我建议您通过 w3schools 等教程网站了解更多信息
  • 请 Samleo,我已经尝试获取一些关于如何在 div id='items' 中附加和显示产品的教程,但我失败了,感谢任何帮助。
【解决方案2】:

经过一番研究,我找到了迄今为​​止最有效和最简单的方法。

let cloneNode = document.querySelectorAll(".item-card");
cloneNode.forEach(element => document.querySelector(".items").appendChild(element.cloneNode(true)) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2019-07-08
    相关资源
    最近更新 更多