search
HomeWeb Front-endJS TutorialjQuery method parsing --append()

jQuery method parsing --append()

Jun 24, 2017 am 11:23 AM
jquerymethodparse

        接下来几天俺会让俺媳妇随机挑几个jq的函数方法,然后我查看源码,以及加入自己的理解写几个博文,如果大家有特别希望了解的可以回复,这样我就不用让俺媳妇挑了。

        今天以及接下来几天的jq均已jq1.7.1这个版本为例。

首先我们来看下jqapi的说明:向每个匹配的元素内部追加内容。


这个操作与对指定的元素执行appendChild方法,将它们添加到文档中的情况类似。

这个方法接收1个参数:content,接受类型有4种(3种从1.0就有了,function从1.4之后开始有)

String:字符串,这个容易理解就是可以直接$("选择器").append("aaaabbbbbcccc");这么写,当然jq内部还支持$("选择器").append('');这种html标签的字符串,至于性能方面咋们后面看源码的时候在细论。

Element:节点,这个也容易理解就是dom节点么基本上俺是写成,$("选择器").append(document.getElementsByTagName("a"))这类,不过这么写的同学要注意一点,这么写会将原来位置的dom给“剪切”到选择器底部,请允许我这么形容。

jQuery:jQuery对象,这注意这个对象是jq选择器加工过的对象,比如$("选择器1").append($(“选择器2”));而不是$("选择器1").append($);写到这俺笑了,应该没人写append($)这个是吧。

function(index, html):一个function对象(参数后面讲),可以写成$("选择器").append(function(index,html){return ""});其中return "" 可以省略,任何函数都有返回值,没写return就会返回undefined,这个貌似高程或者权威指南有讲,具体哪写的,俺也忘记了。index参数为对象在这个集合中的索引值,要解释这句话,我们看个例子吧

var _body=$("body");
_body.html('');//清空body
_body.append("<p></p><p></p>");//插入2个空p
$("p").append(function(){return "a"});//我们要用结果猜个答案,虽然不是必须用这个例子,不过反正到这了 就这么写了

看到结果,俺猜append方法内部对整个选择器进行了遍历jQuery method parsing --append(),然后插入了函数返回的东西。

所以index和html很容易理解了,就是在便利过程中的index和index对应的原先的html(插入之前);

最后讲一下,就是jq本身就是链式调用,所以append()返回的是选择器选择的对象被插之后的新对象jQuery method parsing --append(),讲的好邪恶。

可以$("选择器").append().append().append().......................,不过一般都不会这么玩吧?

解释完API我们来看看源码

看到这个截图...好吧我们继续往下看。

domManip: function (args, table, callback) {
            //定义6个变量,我们先不管这些变量干嘛。
            var results, first, fragment, parent,
			value = args[0],/*args参数在append调用的时候其实只有1个参数*/
			scripts = [];
            /*
            进行了各种判断
                1、!jQuery.support.checkClone:确保文档碎片还没有被克隆(作用在后面)
                2、arguments.length === 3,确保调用domManip这个函数只有3个参数,否则会往后面走,这个很妙
                3、typeof value === "string"确认你的参数是string类型
                4、rchecked.test(value)
            */
            if (!jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test(value)) {
                //遍历选择器,看来我前面的猜测对了
                return this.each(function () {
                    //看每次循环都调用了这个domManip,但是这些调用不会进入这个if,为什么?仔细看上面的注释与下面的调用
                    jQuery(this).domManip(args, table, callback, true);
                });
            }
            //如果参数类型是function的
            if (jQuery.isFunction(value)) {
                //还是遍历
                return this.each(function (i) {
                    var self = jQuery(this);
                    /*
                    记得function的返回值吗?这边就把那边的返回值存到args[0]里面了
                    table ? self.html() : undefined;这句话看不懂?table这个变量,在append调用domManip时已经写死了是true
                    所以在执行function类型参数的时候那个index和html是什么这边已经很明显了
                    */
                    args[0] = value.call(this, i, table ? self.html() : undefined);
                    //取到插入的内容之后,重复第一步......
                    self.domManip(args, table, callback);
                });
            }
            /*
            到了这里,已经确保你取到了function中返回的string
            上面的各种判断已经把你参数处理成接下去想要的,淡定的往下看吧
            if (this[0]) 这个判断。。。确保选择器存在,为什么不放最前面?
            */
            if (this[0]) {
                /*
                取父级节点
                &&运算符就是
                0&&1=0
                1&&2=2
                0&&0=0
                */
                parent = value && value.parentNode;

                // If we&#39;re in a fragment, just use that instead of building a new one
                /*
                如果已经有元素碎片了就用原来的,不然就新建一个
                */
                if (jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length) {
                    results = { fragment: parent };

                } else {
                    results = jQuery.buildFragment(args, this, scripts);
                }

                fragment = results.fragment;
                //取碎片中最后一个
                if (fragment.childNodes.length === 1) {
                    first = fragment = fragment.firstChild;
                } else {
                    first = fragment.firstChild;
                }
                //存在最后一个节点
                if (first) {
                    //确保最后一个元素是tr?
                    table = table && jQuery.nodeName(first, "tr");

                    for (var i = 0, l = this.length, lastIndex = l - 1; i < l; i++) {
                        callback.call(
						table ?
							root(this[i], first) :
							this[i],
                        // Make sure that we do not leak memory by inadvertently discarding
                        // the original fragment (which might have attached data) instead of
                        // using it; in addition, use the original fragment object for the last
                        // item instead of first because it can end up being emptied incorrectly
                        // in certain situations (Bug #8070).
                        // Fragments from the fragment cache must always be cloned and never used
                        // in place.
						results.cacheable || (l > 1 && i < lastIndex) ?
							jQuery.clone(fragment, true, true) :
							fragment
					);
                    }
                }
                /*插入脚本文件的话jq会帮你去请求的*/
                if (scripts.length) {
                    jQuery.each(scripts, function (i, elem) {
                        if (elem.src) {
                            jQuery.ajax({
                                type: "GET",
                                global: false,
                                url: elem.src,
                                async: false,
                                dataType: "script"
                            });
                        } else {
                            jQuery.globalEval((elem.text || elem.textContent || elem.innerHTML || "").replace(rcleanScript, "/*$0*/"));
                        }

                        if (elem.parentNode) {
                            elem.parentNode.removeChild(elem);
                        }
                    });
                }
            }

            return this;
        }


在往里面还有个底层buildFragment方法,我稍微看了,解释起来颇为费劲。

底层代码解释起来麻烦俺就直接注释到源码里面去了,大家瞅瞅 有木有不对的,求斧正,另外大家可以加俺的QQ群:43881427一起讨论讨论前端问题

里面还有.net  SQL的高手哦

The above is the detailed content of jQuery method parsing --append(). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor