【问题标题】:Setting the value for setAttribute by looping through an array通过遍历数组来设置 setAttribute 的值
【发布时间】:2017-03-09 10:21:51
【问题描述】:

我对 JavaScript 很陌生,想使用循环和变量来设置元素的属性。运行下面的例子here

<h1 id="header">START</h1>

<button onclick="run()">run</button>

<script>
  function run()
  {
    var s, myStringArray = ["red", "blue"];
    for (s of myStringArray)
    {
      document.getElementById("header").setAttribute("style","color:"+s);
    }
  }
</script>

这可行,但我想要一个包含setAttribute 完整值的变量数组。

例如:

attribArray = [""style","color:red"", ""style","color:blue""]

这是一个假设性问题,示例代码没有多大意义。

我将如何创建这样一个数组,以便我可以循环遍历它并直接在document.getElementById("header").setAttribute(theVar) 中使用上述变量?

【问题讨论】:

  • 你为什么把文本变成红色然后立即变成蓝色?
  • 如 OP 中所述,这显然没有意义,这只是一个例子。
  • 那么问题陈述没有意义。为什么需要这样做?
  • 我不明白这样的 cmets。我只是试图给出一个我的实际代码的简单示例来简化帖子。

标签: javascript html arrays for-loop attributes


【解决方案1】:

您可以使用对象数组:

function run() {
  var myAttributes = [
    { attr: "style", value: "color: red" },
    { attr: "style", value: "color: blue" }
  ];

  for (var i = 0; i < myAttributes.length; i++) {
    document.getElementById("header").setAttribute(myAttributes[i].attr, myAttributes[i].value);
  }
}
<h1 id="header">START</h1>

<button onclick="run()">run</button>

现在,请记住,您的代码和此 sn-p 将两次更新同一元素的颜色,因此毫无意义。如果要循环颜色,可以执行以下操作:

let current = 0;
function run() {
  var myAttributes = [
    { attr: "style", value: "color: red" },
    { attr: "style", value: "color: blue" },
    { attr: "style", value: "color: yellow" },
    { attr: "style", value: "color: green" }
  ];
  
  document.getElementById("header").setAttribute(myAttributes[current].attr, myAttributes[current].value);
  
  current = current === (myAttributes.length - 1) ? 0 : current + 1;
}
<h1 id="header">START</h1>

<button onclick="run()">run</button>

奖励:ES6 语法

使用 ES6 语法,我们可以让它看起来更友好一些:

function run() {
    let header = document.getElementById("header");
    const myAttributes = [
        { attr: "style", value: "color: red" },
        { attr: "style", value: "color: blue" }
    ];

    for (let { attr, value } of myAttributes) {
        header.setAttribute(attr, value);
    }
}

【讨论】:

  • 这看起来不错!对于 setAttribute 值,有没有办法用可变数量的元素来做到这一点?例如var myAttributes = [""style","color:red"", ""style","color:blue","background-color:black;""]
  • 对于这种情况,您可以执行以下操作:{ attr: "style", value: "color: red; background-color: black;" }。该值可以包含您需要的任意数量的样式。其他任何事情都需要额外的更改。
猜你喜欢
  • 1970-01-01
  • 2020-11-08
  • 2021-09-14
  • 2014-05-13
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多