【问题标题】:How to mix variable and string in js setAttribute() attribute value?如何在 js setAttribute() 属性值中混合变量和字符串?
【发布时间】:2020-11-10 10:51:22
【问题描述】:

这是一个基本问题,但我不知怎么找不到答案。

我想在 setAttribute() 方法中传递字符串和变量的混合值作为属性的值。

这就是我所拥有的:

    document.getElementById('mydiv').setAttribute("style", "width: 10%")

我想要的不是“width: 10%”,而是:“width: --myVar-- %”

我发现的所有问题都与只传递一个变量有关,而不是如何混合变量和字符串。

感谢您的帮助!

【问题讨论】:

  • 你需要将你的字符串与你的变量连接起来。
  • 试试这个:var foo = 20; document.getElementById('mydiv').setAttribute('style', 'width: '+ foo +'px');

标签: javascript string variables setattribute


【解决方案1】:

你可以这样用。

document.getElementById('mydiv').setAttribute("style", "width:"+ myVar+ "%")

【讨论】:

    【解决方案2】:

    当有直接属性和访问器时,你甚至不应该使用 setAttribute:

    document.getElementById('mydiv').style.width = myVar + '%';
    

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2011-07-19
      • 2015-07-29
      相关资源
      最近更新 更多