深入学习jquery源码之before()和after()

深入学习jquery源码之before()和after()

after(content|fn)

概述

在每个匹配的元素之后插入内容。

参数

content String, Element, jQuery

插入到每个目标后的内容

function Function

函数必须返回一个html字符串。

在所有段落之后插入一些HTML标记代码。

<p>I would like to say: </p>
$("p").after("<b>Hello</b>");
<p>I would like to say: </p><b>Hello</b>

在所有段落之后插入一个DOM元素。

<b id="foo">Hello</b><p>I would like to say: </p>
$("p").after( $("#foo")[0] );
<p>I would like to say: </p><b id="foo">Hello</b>

在所有段落中后插入一个jQuery对象(类似于一个DOM元素数组)。

<b>Hello</b><p>I would like to say: </p>
$("p").after( $("b") );
<p>I would like to say: </p><b>Hello</b>

before(content|fn)

概述

在每个匹配的元素之前插入内容。

参数 

content String, Element, jQuery

插入到每个目标后的内容

function Function

函数必须返回一个html字符串。

在所有段落之前插入一些HTML标记代码。

<p>I would like to say: </p>
$("p").before("<b>Hello</b>");
[ <b>Hello</b><p>I would like to say: </p> ]

在所有段落之前插入一个元素。

<p>I would like to say: </p><b id="foo">Hello</b>
$("p").before( $("#foo")[0] );
<b id="foo">Hello</b><p>I would like to say: </p>

在所有段落中前插入一个jQuery对象(类似于一个DOM元素数组)。

<p>I would like to say: </p><b>Hello</b>
$("p").before( $("b") );
<b>Hello</b><p>I would like to say: </p>

insertAfter(content)

概述

把所有匹配的元素插入到另一个、指定的元素元素集合的后面。

实际上,使用这个方法是颠倒了常规的$(A).after(B)的操作,即不是把B插入到A后面,而是把A插入到B后面。

在jQuery 1.3.2中,appendTo, prependTo, insertBefore, insertAfter, 和 replaceAll这个几个方法成为一个破坏性操作,要选择先前选中的元素,需要使用end()方法,参见 appendTo 方法的例二。

参数

content String

用于匹配元素的jQuery表达式

把所有段落插入到一个元素之后。与 $("#foo").after("p")相同

<p>I would like to say: </p><div id="foo">Hello</div>
$("p").insertAfter("#foo");
<div id="foo">Hello</div><p>I would like to say: </p>

insertBefore(content)

概述

把所有匹配的元素插入到另一个、指定的元素元素集合的前面。

实际上,使用这个方法是颠倒了常规的$(A).before(B)的操作,即不是把B插入到A前面,而是把A插入到B前面。

在jQuery 1.3.2中,appendTo, prependTo, insertBefore, insertAfter, 和 replaceAll这个几个方法成为一个破坏性操作,要选择先前选中的元素,需要使用end()方法,参见 appendTo 方法的例二。

参数

content String

用于匹配元素的jQuery表达式

把所有段落插入到一个元素之前。与 $("#foo").before("p")相同。

<div id="foo">Hello</div><p>I would like to say: </p>
$("p").insertBefore("#foo");
<p>I would like to say: </p><div id="foo">Hello</div>

jquery源码

       jQuery.each({
        insertBefore: "before",
        insertAfter: "after"
    }, function (name, original) {
        jQuery.fn[name] = function (selector) {
            var elems,
                i = 0,
                ret = [],
                insert = jQuery(selector),
                last = insert.length - 1;

            for (; i <= last; i++) {
                elems = i === last ? this : this.clone(true);
                jQuery(insert[i])[original](elems);

                // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
                push.apply(ret, elems.get());
            }

            return this.pushStack(ret);
        };
    });



   jQuery.fn.extend({
        before: function () {
            return this.domManip(arguments, function (elem) {
                if (this.parentNode) {
                    this.parentNode.insertBefore(elem, this);
                }
            });
        },

        after: function () {
            return this.domManip(arguments, function (elem) {
                if (this.parentNode) {
                    this.parentNode.insertBefore(elem, this.nextSibling);
                }
            });
        },
		
        domManip: function (args, callback) {

            // Flatten any nested arrays
            args = concat.apply([], args);

            var first, node, hasScripts,
                scripts, doc, fragment,
                i = 0,
                l = this.length,
                set = this,
                iNoClone = l - 1,
                value = args[0],
                isFunction = jQuery.isFunction(value);

            // We can't cloneNode fragments that contain checked, in WebKit
            if (isFunction ||
            (l > 1 && typeof value === "string" &&
                !support.checkClone && rchecked.test(value))) {
                return this.each(function (index) {
                    var self = set.eq(index);
                    if (isFunction) {
                        args[0] = value.call(this, index, self.html());
                    }
                    self.domManip(args, callback);
                });
            }

            if (l) {
                fragment = jQuery.buildFragment(args, this[0].ownerDocument, false, this);
                first = fragment.firstChild;

                if (fragment.childNodes.length === 1) {
                    fragment = first;
                }

                if (first) {
                    scripts = jQuery.map(getAll(fragment, "script"), disableScript);
                    hasScripts = scripts.length;

                    // Use the original fragment for the last item instead of the first because it can end up
                    // being emptied incorrectly in certain situations (#8070).
                    for (; i < l; i++) {
                        node = fragment;

                        if (i !== iNoClone) {
                            node = jQuery.clone(node, true, true);

                            // Keep references to cloned scripts for later restoration
                            if (hasScripts) {
                                jQuery.merge(scripts, getAll(node, "script"));
                            }
                        }

                        callback.call(this[i], node, i);
                    }

                    if (hasScripts) {
                        doc = scripts[scripts.length - 1].ownerDocument;

                        // Reenable scripts
                        jQuery.map(scripts, restoreScript);

                        // Evaluate executable scripts on first document insertion
                        for (i = 0; i < hasScripts; i++) {
                            node = scripts[i];
                            if (rscriptType.test(node.type || "") &&
                                !jQuery._data(node, "globalEval") && jQuery.contains(doc, node)) {

                                if (node.src) {
                                    // Optional AJAX dependency, but won't run scripts if not present
                                    if (jQuery._evalUrl) {
                                        jQuery._evalUrl(node.src);
                                    }
                                } else {
                                    jQuery.globalEval((node.text || node.textContent || node.innerHTML || "").replace(rcleanScript, ""));
                                }
                            }
                        }
                    }

                    // Fix #11809: Avoid leaking memory
                    fragment = first = null;
                }
            }

            return this;
        }
    });
	
	

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/85329098