4

jQuery.fn.empty()remove()函数异步执行吗?我在 jQuery 文档的任何地方都找不到这个问题的答案。

4

3 回答 3

9

它们都是同步的。您可以查看实际实现的源代码:

remove: function( selector, keepData ) {
    var elem,
        elems = selector ? jQuery.filter( selector, this ) : this,
        i = 0;

    for ( ; (elem = elems[i]) != null; i++ ) {
        if ( !keepData && elem.nodeType === 1 ) {
            jQuery.cleanData( getAll( elem ) );
        }

        if ( elem.parentNode ) {
            if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
                setGlobalEval( getAll( elem, "script" ) );
            }
            elem.parentNode.removeChild( elem );
        }
    }

    return this;
},

empty: function() {
    var elem,
        i = 0;

    for ( ; (elem = this[i]) != null; i++ ) {
        if ( elem.nodeType === 1 ) {

            // Prevent memory leaks
            jQuery.cleanData( getAll( elem, false ) );

            // Remove any remaining nodes
            elem.textContent = "";
        }
    }

    return this;
},

你可以忽略keepDataandcleanData东西,所以剩下的就是一个循环和一个对本地 DOM 方法的调用或一个 DOM 对象属性修改。这些都是同步的。

于 2013-06-10T18:00:31.610 回答
2

不,它们是可链接的方法,因此它们会在返回原始 jQuery 对象之前完成。

于 2013-06-10T17:59:14.443 回答
1

They are synchronous, if there is a reason for you to want them to be asynchronous (Wait until the current execution path finishes, and then empty the queue sometime), you can do:

// Empty asynchronously
setTimeout(function(){
    $('...').empty();
}, 0);
于 2013-06-10T18:04:31.237 回答