Javascript 脚本元素设置内部文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11000052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript script element set inner text
提问by VSP
We need to add a javascript element inside an iframe (its inside the same web/domain so no security problems attached). We got it working but dont know how to fill the script content betwen its tags...how would you do it?
我们需要在 iframe 中添加一个 javascript 元素(它在同一个 web/域中,因此没有附加安全问题)。我们让它工作了,但不知道如何在它的标签之间填充脚本内容......你会怎么做?
var iframe = document.getElementById('iframeX');
var iframedocument = iframe.contentWindow.document;
var script = iframedocument.createElement('script');
script.setAttribute('type', 'text/javascript');
script.innerText = 'alert(\'hello\')'; //this doesnt work
script.value= 'alert(\'hello\')'; //this doesnt work either
var head = iframedocument.getElementsByTagName("head")[0];
head.appendChild(script);
Desired result in the iframe document:
iframe 文档中的期望结果:
<head>
<script type="text/javascript" >
alert('hello');
</script>
</head>
回答by Praveen Kumar Purushothaman
Did you try:
你试过了吗:
script.setAttribute('type', 'text/javascript');
script.innerHTML = 'alert(\'hello\')';
回答by Maju
I had problem with script.innerHTML as it doesn't work in IE8-.
我对 script.innerHTML 有问题,因为它在 IE8- 中不起作用。
script.text = 'alert(\'hello\')';
script.text works better for me. Found on: Create script tag in IE8
script.text 对我来说效果更好。发现于:在 IE8 中创建脚本标记