(我今天早些时候遇到了类似的问题,但现在不同了)。我有一个代码来创建一个元素,为它们设置属性,最后,附加到父 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>
相关分类