使用 Javascript 缩短重复/多个属性



我正在尝试通过重复属性传播值以设置某些节点的内容。我这样做的方式是有效的。 但是,正如我所提到的,这是重复的,而且看起来有点令人沮丧。还有其他方法可以缩短我的代码吗?

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...
}

。其中 "post" = JSON.parse(this.response(;

任何有助于缩短这一负担的帮助都是值得赞赏的。谢谢。

我会使用一个将属性名称映射到选择器的对象:

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];

也不需要循环,因为你只做一次。

最新更新