使用innnerHTML来移除相关内容确实很方便,但如果元素内设置了事件监听器,当元素被移除时,IE并不会解除元素与事件之间的关联,这样很容易导致内存泄漏(资源无法利用,也无法回收),因为事件引用的内容已经不存在了
因此,要设计一个移除元素同时移除监听事件的函数 思路: 1、设计一个判断该属性是否为函数的函数 2、通过遍历移除节点 3、获取节点自身带有的属性,结合1,若是函数则将其置为null
function isFun(f){ return Object.PRototype.toString.call(f)==="[object Function]";}function removeDom(node){ var i,len,attr; while(node.firstChild){ removeDom(node.firstChild); } len=node.attributes?node.attributes.length:0; for(i=0;i<len;i++){ attr=node[node.attributes[i].name]; if(isFun(attr)){ attr=null; } } node.parentNode.removeChild(node);}新闻热点
疑难解答