如何解决将JS制成的HTML元素放入实际HTML正文中的问题?

时间:2019-05-14 20:10:19

标签: javascript html mysql node.js

我试图循环一个数组,并将所有行标题作为单独的标头放在我的HTML正文中。创建 P 标签并将其附加可以,但是现在我制作了一个完整的html元素,并希望将其附加到正文中,但这似乎不起作用。

for (let i = 0; i < rows.length; i++) {
    //var para = document.createElement("P"); 
    //para.innerText = rows[i].titel;
    //document.body.appendChild(para);

    var titel = rows[i].titel;
    var post = "<div class='card-body'>\
                <h5 class='card-title'>"+ titel + "</h5>\
                <a href='oefeningDetail.html' class='btn btn-primary'>details</a>\
                </div>";

    console.log(post);
    document.body.appendChild(post);
}

2 个答案:

答案 0 :(得分:2)

问题是 appendChild()函数需要html元素作为参数-您正在尝试传递字符串。

您可以改为使用 .innerHTML 属性。

  var post = "<div class='card-body'>\
                            <h5 class='card-title'>" + titel + "</h5>\
                            <a href='oefeningDetail.html' class='btn btn-primary'>details</a>\
                            </div>";
  document.body.innerHTML = post;

答案 1 :(得分:0)

正如@obscure所提到的,之所以不起作用,是因为appendChild()需要一个node类型的参数值才能起作用。他提供了一个带有innerHTML属性的替代方案,但是,正如评论中提到的@Walk一样,它还有一些附加的安全风险,因此appendChild()方法可能仍然是最佳选择。

鉴于您要遍历并添加多个元素,创建一个元素“模板”并将其克隆到循环中可能是最简单的:

// Create "card-body" template
var elementTemplate = document.createElement("div");
elementTemplate.setAttribute("class", "card-body");

// Create "card-title" template
var headerTemplate = document.createElement("h5");
headerTemplate.setAttribute("class", "card-title");

// Create button template
var linkTemplate = document.createElement("a");
linkTemplate.setAttribute("href", "oefeningDetail.html");
linkTemplate.setAttribute("class", "btn btn-primary");
linkTemplate.textContent = "details";

// Append "card-title" and button to the "card-body" template
elementTemplate.appendChild(headerTemplate);
elementTemplate.appendChild(linkTemplate);

// Now that you have a template to work with . . .

// Loop through the rows
for (let i = 0; i < rows.length; i++) {
    // Create local deep copy of the "card-body" template
    var newElement = elementTemplate.cloneNode(true);

    // Update the "card-title" header in the new element with the "titel" value
    newElement.querySelector(".card-title").textContent = rows[i].titel;

    // Append the new element to the body
    document.body.appendChild(newElement);
}