让innerHTML的脚本也可以运行起来
最近在脑子一直在想pjblog重构的问题.当然重构前,必须把所有需要做的东西想清楚.其中想到一个js改进的内容,需要innerHTML后的脚本也
可以运行.但是尝试了一下.发现IE下直接innerHTML的脚本无法执行.
尝试了几次发现,插入的HTML里,<script>前面有其他对象,并且script 设置了 defer ,
这样的脚本innerHTML被IE执行了.
,但是这招对于firefox不灵~~
后来找了一些资料发现 firefox 把对象重新 append 或者 insertBefore 一次就可以执行里面的脚本了.
程序代码
var fillHTML = function (el,HTMLString) {
if (!el) return;
if (window.ActiveXObject) { //For IE
el.innerHTML = "<img style='display:none'/>" + HTMLString.replace(/<script([^>]*)>/ig, '<script$1 defer>');
el.removeChild(el.firstChild)
} else { //For Mozilla,Opare
var nSibling = el.nextSibling;
var pNode = el.parentNode;
pNode.removeChild(el);
el.innerHTML = HTMLString;
pNode.insertBefore(el,nSibling)
}
}
作者:puterjam 来自pjhome
![](http://www.pjhome.net/images/smilies/Face_03.gif)
![](http://www.pjhome.net/images/smilies/Face_10.gif)
![程序代码](http://www.pjhome.net/images/code.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
作者:puterjam 来自pjhome