2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的代碼存在多個(gè)問題。
首先,在引用變量時(shí),您使用的是帶有名稱的字符串。這是錯(cuò)誤的,您可以而且應(yīng)該只使用它而不使用引號(hào)。像這樣:
reference.appendChild("spanner");
reference.appendChild("thepic");
outer.appendChild("reference");
應(yīng)該
reference.appendChild(spanner);
reference.appendChild(thepic);
outer.appendChild(reference);
其次,更重要的是,您可能應(yīng)該使用一些模板引擎來做這類事情。手動(dòng)更換會(huì)很快變得很麻煩。你不必使用現(xiàn)代和花哨的框架(如 React、Angular、Vue 等)來做到這一點(diǎn)。例如,您可以檢查https://github.com/janl/mustache.js或https://ejs.co/ 之類的內(nèi)容,讓您的生活更輕松。

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
通過多行字符串和變量插值,您可以直接在代碼中使用 HTML。插入方法是insertAdjacentHTML。
const clss = "landscape";
const src = "images/landscape/land_01.jpg";
const href = "images/landscape/land_01.jpg";
const html = `<div class="item ${clss} col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4 mb-4">
<a href="${href}" class="item-wrap fancybox">
<span class="icon-search2"></span>
<img class="img-fluid" src="${src}">
</a>
</div>`
const container = document.getElementById("container");
container.insertAdjacentHTML("beforeend", html);
alert(container.outerHTML);
<div id="container">the container</div>
添加回答
舉報(bào)