调用html()之前需要执行unbind()还是off()

Is it required to do unbind() or off() before calling html()

本文关键字:执行 unbind 还是 off html 调用      更新时间:2023-09-26

在调用jQuery html()之前,是否需要对html元素执行jQuery unbind()off()函数以避免内存泄漏?

不,这不是必需的。

html功能负责在设置innerHTML之前清洁所有东西。

来自文件:

此外,jQuery还删除了数据和事件等其他构造处理程序,然后将这些元素替换为新内容。


实施细节:

html函数调用empty,其代码如下:

empty: function() {
    var elem,
        i = 0;
    for ( ; (elem = this[i]) != null; i++ ) {
        // Remove element nodes and prevent memory leaks
        if ( elem.nodeType === 1 ) {
            jQuery.cleanData( getAll( elem, false ) );
        }
        // Remove any remaining nodes
        while ( elem.firstChild ) {
            elem.removeChild( elem.firstChild );
        }
        // If this is a select, ensure that it displays empty (#12336)
        // Support: IE<9
        if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
            elem.options.length = 0;
        }
    }
    return this;
},