【发布时间】:2017-10-05 01:26:55
【问题描述】:
我有一串用有效 html 编写的属性,我想将这些属性放在实际的 html element 上(而不是元素的 html string)。
例如,我在合理命名的attributesStr 变量中有属性字符串,我想将这些属性添加到#htmlElement div。
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
The HTML element!
</div>
运行 JQuery / JavaScript 代码后,#htmlElement 应如下所示:
<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue>
The HTML element!
</div>
如何在 JavaScript 或 Jquery 中做到这一点?
第一次尝试:我想我可以通过 .split()ing attributesStr 在空格上执行此操作,然后在 = 上拆分每个单独的属性键值对,然后迭代该数组并添加每个键值对使用 JQuery 的 .prop() 或 .attr(),但这不起作用有两个原因:
-
style和title属性会失败,因为它们有空格。 - 它可能在没有值的属性上失败。
【问题讨论】:
-
attributesStr.match(/[^\s=]+(=['][^']*['])?/g)这会让你第一次分裂 -
您通过破解预先构建的字符串使这变得比需要的更难。您不能在构建该字符串时应用样式吗?或者甚至创建一个具有这些值的对象以供以后应用?
-
@RoryMcCrossan 我已经找到了一个不同的解决方案来解决我原来的问题,我只是好奇是否有办法在 JS/JQuery 中做到这一点:)
-
@tallberg 如果您认为自己有一个可行的解决方案,请随时发布答案:)
-
当然,有很多方法可以做任何事情,但由于各种原因,其中大多数都不是最好的方法。
标签: javascript jquery html attributes