[英]Using HTML DOM to change contents of Script Tag
当我们使用 html dom 时,我们通常运行如下代码:
document.getElementById('id').innerHTML = 'new text'
更改标签的内容,例如<div>
但是我用<script>
标签尝试了这个,它似乎没有工作。 我应该尝试什么?
document.getElementsByTagName('script')[0].innerHTML = "document.write('ok')"
假设您有一组脚本:
var scripts = document.getElementsByTagName('script');
执行scripts[0].innerHTML = "document.write('ok')"
将有效地更改脚本的内容,但不会执行脚本的新内容。
解决方案很简单:
body
中。 它将被执行。 使用body
中的待更新脚本,这等于:
document.body.removeChild(scripts[0]);
var newScript = document.createElement('script');
newScript.innerHTML = 'document.write("ok")';
document.body.appendChild(newScript);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.