empty(): removes all data and event handlers from the removed elements.
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
因此在每次使用html(content)时,如果不想保留数据及事件的话(使用html()常常是如此的), 最好先使用empty();
/**normal**/
$("#matched").html(htmlString);
->
/**better**/
$("#matched").empty().html(htmlString);
在大型程序中,使用前一种方案很可能会造成页面闪动(当自己忘记移除相关的数据和事件时),使用后一种方案更安全。
本文探讨了jQuery中empty()方法的用途及其在避免内存泄漏方面的重要性,并对比了使用html()与empty().html()的不同之处,强调了后者在大型项目中的优势。
247

被折叠的 条评论
为什么被折叠?



