【发布时间】:2020-01-04 06:21:20
【问题描述】:
(我今天早些时候遇到了类似的问题,但现在不同了)。我有一个创建元素的代码,为它们设置属性,最后附加到父 div。
我已经试过了:
Object.entries(selectorsByProp).forEach(([prop, selector]) => {
document.querySelector(selector).innerHTML = post[i][prop];
});
这确实有效,但它只能操纵显示和显示我的数据的元素。我需要的是它必须创建元素、设置属性和追加。这是我荒谬的代码...
var post = JSON.parse(this.response);
for (var i = 0; i < 3; i++) {
var listcard = document.createElement("div"),
imgcontent = document.createElement("div"),
imgcntnr = document.createElement("div"),
imglnk = document.createElement("a"),
a = document.createElement("a"),
img = document.createElement("img"),
txtcntnt = document.createElement("div"),
span = document.createElement("span");
listcard.setAttribute('class', 'list-card');
imgcontent.setAttribute('class', 'img-content');
imgcntnr.setAttribute('class', 'img-container');
imglnk.setAttribute('href', '#');
img.setAttribute('class', 'thumb');
txtcntnt.setAttribute('class', 'text-content');
a.setAttribute('href', '#');
a.setAttribute('class', 'title');
span.setAttribute('class', 'excerpt');
img.setAttribute('src', post[i].img);
img.setAttribute('alt', post[i].titles);
a.innerHTML = post[i].titles;
span.innerHTML = post[i].descs;
imglnk.appendChild(img);
imgcntnr.appendChild(imglnk);
imgcontent.appendChild(imgcntnr);
txtcntnt.innerHTML += a.outerHTML + span.outerHTML;
listcard.innerHTML += imgcontent.outerHTML + txtcntnt.outerHTML;
parent.appendChild(listcard);
}
<div class="list-card">
<div class="img-content">
<div class="img-container">
<a href="#"> <img src="https://picsum.photos/182/135/?random" alt="" class="thumb"></a>
</div>
</div>
<div class="text-content">
<a href="#" class="title">Lorem Ipsum</a>
<span class="excerpt">Lorem Ipsum</span>
</div>
</div>
【问题讨论】:
-
试试mustache或类似的模板引擎。
标签: javascript html json dom