innerhtml 属性的使用非常流行,因为他提供了简单的方法完全替代一个 html 元素的内容。另外一个方法是使用 dom level 2 api(removechild, createelement, appendchild)。但很显然,使用 innerhtml 修改 dom tree 是非常容易且有效的方法。然而,你需要知道 innerhtml 有一些自身的问题: 当 html 字符串包含一个标记为 defer 的 script 标签()时,如 innerhtml 属性处理不当,在 internet explorer 上会引起脚本注入攻击。 设置 innerhtml 将会破坏现有的已注册了事件处理函数的 html 元素,会在某些浏览器上引起内存泄露的潜在危险。
还有几个其他次要的缺点,也值得一提的: 你不能得到刚刚创建的元素的引用,需要你手动添加代码才能取得那些引用(使用 dom apis)。 你不能在所有浏览器的所有 html 元素上设置 innerhtml 属性(比如,internet explorer 不允许你在表格的行元素上设置innerhtml 属性)。
我更关注与使用 innerhtml 属性相关的安全和内存问题。很显然,这不是新问题,已经有能人围绕这些中的某些问题想出了方法。
douglas crockford 写了一个 清除函数 ,该函数负责中止由于 html 元素注册事件处理函数引起的一些循环引用,并允许垃圾回收器(garbage collector)释放与这些 html 元素关联的内存。
从 html 字符串中移除 script 标签并不像看上去那么容易。一个正则表达式可以达到预期效果,虽然很难知道是否覆盖了所有的可能性。这里是我的解决方案:
/
现在,让我们将这两种技术结合在到一个单独的 setinnerhtml 函数中,并将 setinnerhtml 函数绑定到 yui 的 yahoo.util.dom 上:
yahoo.util.dom.setinnerhtml = function (el, html) {
el = yahoo.util.dom.get(el);
if (!el || typeof html !== 'string') {
return null;
}
// 中止循环引用
(function (o) {
var a = o.attributes, i, l, n, c;
if (a) {
l = a.length;
for (i = 0; i n = a[i].name;
if (typeof o[n] === 'function') {
o[n] = null;
}
}
}
a = o.childnodes;
if (a) {
l = a.length;
for (i = 0; i c = o.childnodes[i];
// 清除子节点
arguments.callee(c);
// 移除所有通过yui的addlistener注册到元素上所有监听程序
yahoo.util.event.purgeelement(c);
}
}
})(el);
// 从html字符串中移除script,并设置innerhtml属性
el.innerhtml = html.replace(/