为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3242003 2021-09-30 17:02:25
我试图通过重复属性传播值以设置某些节点的内容。我这样做的方式很有效。然而,正如我所提到的,它是重复的,看起来有点令人沮丧。有没有其他方法可以缩短我的代码?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 回答

?
胡说叔叔

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

也不需要循环,因为您只执行一次。


查看完整回答
反对 回复 2021-09-30
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信