我想做这样的事情但是我得到了一个"无效的左手边和#34;错误。
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://example.com/example.js";
s.data-flix-distributor = "12994";
答案 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";
答案 1 :(得分:0)
设置data-
属性的首选方法是element.dataset
。与样式一样,将自动从dasherized转换为camelCase格式,反之亦然。所以
s.dataset.flixDistributor = "12994";
的产率:
<div data-flix-distributor="12994"></div>