jQuery method parsing --append()
接下来几天俺会让俺媳妇随机挑几个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方法内部对整个选择器进行了遍历,然后插入了函数返回的东西。
所以index和html很容易理解了,就是在便利过程中的index和index对应的原先的html(插入之前);
最后讲一下,就是jq本身就是链式调用,所以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'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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better
