How to insert javascript using innerHTML (ie6 is giving me a unknown runtime error)
1 2 3 4 5 | var head =document.getElementsByTagName("head")[0]; newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.innerHTML = '$(window).load(function(){ someFooo(); }); '; head.appendChild(newScript); |
这导致IE6中出现未知的运行时错误。还有别的办法吗?
而不是:"
1 | newScript.text = '$(window).load(function(){ someFooo(); });'; |
本工程在非IE浏览器为好。我用这ff2,FF3,ff3.5,Safari,Opera 9 4(Win)3 2 +,铬,铬,和他们所有的工作。
根据规格的(我说这对于成本,否则很难),你应该使用
1 2 | var script = '$(window).load(function(){ someFooo(); });'; newScript.appendChild(document.createTextNode(script)); |
我失败了,但在IE(
看起来这是一个问题中使用的元素的innerHTML是只读的。发生这种情况时,你可以尝试在tbody innerHTML设置。根据MSDN文档:
(...) Doing this can also be a little
tricky because you cannot use
innerHTML to inject into the HEAD or
STYLE element directly. (Both of these
tags are READ ONLY.) The best way to
dynamically add styles to a page is to
wait for the document to load, and
then create the rule in a new style
sheet.
为什么它是一个只读属性?这里是一个解释。
所以,你需要使用DOM的动态加载的方法这样做。检查此链接到外部资源的负载和一个内联的JavaScript脚本,这是您的案例。
1 2 3 4 5 6 | newScript = document.createElement('script'); newScript.type = 'text/javascript'; var head = document.getElementsByTagName("head")[0]; var src = '$(window).load(function(){ someFooo(); }); '; newScript.text = src; head.appendChild(newScript); |