簡體   English   中英

如何解決將JS制成的HTML元素放入實際HTML正文中的問題?

[英]How to fix putting JS made HTML element into the actual HTML body?

我試圖循環一個數組,並將所有行標題作為單獨的標頭放在我的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);
}

問題在於, 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;

正如@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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM