慕妹3242003
2021-09-30 17:02:25
我試圖通過重復(fù)屬性傳播值以設(shè)置某些節(jié)點(diǎn)的內(nèi)容。我這樣做的方式很有效。然而,正如我所提到的,它是重復(fù)的,看起來有點(diǎn)令人沮喪。有沒有其他方法可以縮短我的代碼?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);任何有助于減輕這種負(fù)擔(dān)的幫助都是值得贊賞的。謝謝你。
1 回答

胡說叔叔
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
我會(huì)使用一個(gè)將屬性名稱映射到選擇器的對(duì)象:
const selectorsByProp = {
titles: 'h1.title',
dates: '.article-date',
sources: '.source',
// ...
}
Object.entries(selectorsByProp).forEach(([prop, selector]) => {
document.querySelector(selector).innerHTML = post[i][prop];
});
請(qǐng)注意,如果對(duì)象值碰巧僅包含純文本,則分配給textContent元素的 而不是innerHTML:
document.querySelector(selector).textContent = post[i][prop];
也不需要循環(huán),因?yàn)槟粓?zhí)行一次。
添加回答
舉報(bào)
0/150
提交
取消