我正在使用从 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);
这似乎是一个简单的语法错误:
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;
appendChild()
将子节点插入父节点。
// You can also use a class name like this '.some-class-name'
const parentElement = document.querySelector("#some-id");
// Create the child element, it can be anything.
const childElement = document.createElement("p");
childElement.innerHTML = "some name";
parentElement.appenChild(childElement);
现在您可以使用上面的示例来创建一段可以插入多个子元素的代码。