2

我正在寻找 jQuery 的 .appendTo 函数实现。
我尝试在以下位置查找函数:http ://code.jquery.com/jquery-latest.js ,但我只能找到 2 次提及它,并且两者都不包含定义。

我可以在哪里找到它的任何想法?

谢谢你,尼夫。

4

1 回答 1

1

It's actually quite cool: appendTo is dynamically defined relative to append. That's what is going on in these lines:

jQuery.each({
    appendTo: "append",
    prependTo: "prepend",
    insertBefore: "before",
    insertAfter: "after",
    replaceAll: "replaceWith"
}, function( name, original ) {
    jQuery.fn[ name ] = function( selector ) {
        var ret = [],
            insert = jQuery( selector ),
            parent = this.length === 1 && this[0].parentNode;
...

Which makes sense, as the two functions are almost the same in functionality, just reversed in which effects which.

Should you include that file, then pass the function $('html').appendTo and analyze what it references, you get this:

function ( selector ) {
    var ret = [],
        insert = jQuery( selector ),
        parent = this.length === 1 && this[0].parentNode;
...

Do you recognize that code? If you continue down the first code block I mentioned, you'll see they're almost identical. The first block dynamically generates the code for appendTo, as well as a few others in the same vein.

于 2012-08-09T15:57:43.817 回答