我正在尝试在动态创建的JavaScript属性中添加data-client-key
。检查以下代码,我尝试了什么:
var script = document.createElement("script")
script.type = "text/javascript";
script.src = 'https://app.example.com/snap/script.js';
//script.data-client-key="CLIENT-KEY-HERE"; /* showing error message */
document.getElementsByTagName(script)[0].setAttribute("data-client-key", "CLIENT-KEY-HERE"); /* Uncaught TypeError: Cannot read property 'setAttribute' of undefined */
document.getElementsByTagName("head")[0].appendChild(script);
当我检查元素时,我的输出应如下所示:
<script src="https://app.example.com/snap/script.js" data-client-key="CLIENT-KEY-HERE"></script>
答案 0 :(得分:3)
更改
document.getElementsByTagName(script)[0].setAttribute("data-client-key", "CLIENT-KEY-HERE");
到
script.setAttribute("data-client-key", "CLIENT-KEY-HERE");
因为您的脚本元素已经在script
变量中
答案 1 :(得分:1)
请查看以下documentation中的setAttribute。你可以这样
b.setAttribute("name", "helloButton");