使用Javascript缩短重复/多个属性
我试图通过重复属性传播这些值,以设置某些节点的内容。我这样做是有效的。然而,正如我所提到的,它是重复的,并且有点令人沮丧。有没有其他方法可以缩短我的代码使用Javascript缩短重复/多个属性,javascript,for-loop,dom,Javascript,For Loop,Dom,我试图通过重复属性传播这些值,以设置某些节点的内容。我这样做是有效的。然而,正如我所提到的,它是重复的,并且有点令人沮丧。有没有其他方法可以缩短我的代码 for (var i = 0; i < 1; i++) { var title = document.querySelector("h1.title"), date = document.querySelector(".article-date"), tme = document.querySele
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...
}
for(变量i=0;i<1;i++){
var title=document.querySelector(“h1.title”),
日期=document.querySelector(“.article date”),
tme=document.querySelector(“.article tme”),
src=document.querySelector(“.source”),
user=document.querySelector(“.user”),
tip=document.querySelector(“.tip”);
//…其他一些变量。。。
title.innerHTML=post[i]。标题;
date.innerHTML=post[i]。日期;
src.innerHTML=post[i]。来源;
tme.innerHTML=post[i]。次;
user.innerHTML=post[i]。作者;
tip.innerHTML=post[i]。摘录;
//…其他一些HTML内容设置。。。
}
…其中“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];
也不需要循环,因为您只做了一次。现在是IE。您可能在几个小时前就认识我了,我是关于IE问题的。Object.entries在IE中也不起作用,即使我为此使用了polyfill。有没有办法纠正这个问题?