我正在尝试将脚本动态传递给iframe,因此它将使用此代码段在那里运行(示例中的content
来自服务器):
content = '<script type="text/javascript">document.write("<a href="http://www.example.com" target="_blank">bla</a>"");</script>';
el = document.getElementById('iframeName');
iframeDoc = el.contentWindow.document;
tempEl = iframeDoc.createElement('div');
tempEl.innerHTML = content;
它在新浏览器上运行得很好但是当我尝试在IE8及更低版本上运行它时,innerHTML会出现空值。
我尝试了不同的方法,但内部HTML是我能想到的唯一可以运行我传入tempEl的脚本的选项。关于如何将content
传递给tempEl.innerHTML
的任何想法,以便运行脚本并在IE8上运行 - ?
答案 0 :(得分:0)
您是否尝试将脚本元素注入文档的头部?
我不确定script
代码,但您必须将link
和style
元素注入文档的头部,以便旧版IE浏览器正确解释。< / p>
var script = document.createElement('script');
script.type = 'text/javascript';
script.rel = 'JavaScript';
script.innerHTML = 'document.write("<a href=\"http://www.example.com\" target=\"_blank\">bla</a>");';
var el = document.getElementById('iframeName');
iframeDoc = el.contentWindow.document;
iframeDoc.head.appendChild(script);
答案 1 :(得分:0)
我选择的解决方案是:
el = document.getElementById('iframeName');
iframeDoc = el.contentWindow.document;
iframeDoc.write(content);
它更短,并且是跨浏览器(而不是使用innerHTML)。