我试图通过重复属性传播值以设置某些节点的内容。我这样做的方式很有效。然而,正如我所提到的,它是重复的,看起来有点令人沮丧。有没有其他方法可以缩短我的代码?for (var i = 0; i < 1; i++) { var title = document.querySelector("h1.title"), date = document.querySelector(".article-date"), tme = document.querySelector(".article-tme"), src = document.querySelector(".source"), user = document.querySelector(".user"), tip = document.querySelector(".tip"); //.....some other variables... title.innerHTML = post[i].titles; date.innerHTML = post[i].dates; src.innerHTML = post[i].sources; tme.innerHTML = post[i].times; user.innerHTML = post[i].authors; tip.innerHTML = post[i].excerpts; //....some other HTML content setting...}... where "post" = JSON.parse(this.response);任何有助于减轻这种负担的帮助都是值得赞赏的。谢谢你。
1 回答
![?](http://img1.sycdn.imooc.com/54584f9d0001219b02200220-100-100.jpg)
胡说叔叔
TA贡献1804条经验 获得超8个赞
我会使用一个将属性名称映射到选择器的对象:
const selectorsByProp = {
titles: 'h1.title',
dates: '.article-date',
sources: '.source',
// ...
}
Object.entries(selectorsByProp).forEach(([prop, selector]) => {
document.querySelector(selector).innerHTML = post[i][prop];
});
请注意,如果对象值碰巧仅包含纯文本,则分配给textContent元素的 而不是innerHTML:
document.querySelector(selector).textContent = post[i][prop];
也不需要循环,因为您只执行一次。
添加回答
举报
0/150
提交
取消