如何在名称中将带有连字符的属性添加到脚本元素中?

时间:2017-06-23 16:36:10

标签: javascript

我想做这样的事情但是我得到了一个"无效的左手边和#34;错误。

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://example.com/example.js";
s.data-flix-distributor = "12994";

2 个答案:

答案 0 :(得分:4)

如果您想使用dot notation设置属性,那么它应该是有效的标识符,其他情况下使用bracket notation

参考:custom attribute works only with element.getAttribute("attribute") but not "element.attribute"

要使用setAttribute()方法为元素设置属性。

s.setAttribute('data-flix-distributor', "12994");

或在dataset属性中更新。

s.dataset['flix-distributor'] = "12994";

// or you can use camelCase to dash-style to use dot notation
s.dataset.flixDistributor = "12994";

参考:Name conversion in dataset property

答案 1 :(得分:0)

设置data-属性的首选方法是element.dataset。与样式一样,将自动从dasherized转换为camelCase格式,反之亦然。所以

s.dataset.flixDistributor = "12994";

的产率:

<div data-flix-distributor="12994"></div>