jQuery development experience library
jQuery is a cross-browser JavaScript library that simplifies operations between HTML and JavaScript. 59% of the world's top 10,000 most visited websites use jQuery, which is currently the most popular JavaScript library. In this article, we will discuss the jQuery development experience library in an all-round way.
Preface
#When I was thinking about why jQuery can directly $ operate, it can have more convenient DOM operations than native js, and as long as you You can chain the operation directly if you want
Core Framework
Uncover the jQuery core code of more than 10,000 lines of code:
<span style="font-size: 14px;">(function(window, undefined) {<br> function jQuery(selector){<br> return new jQuery.fn.init(selector)<br> }<br> jQuery.fn = jQuery.prototype = {<br> init: function () {<br><br> }<br> }<br> jQuery.fn.init.prototype = jQuery.fn;<br> window.jQuery = window.$ = jQuery;<br>})(window)<br></span>
Closure structure parameter window
Reduce each internal reference Query time of window
Convenient to compress the code
The closure structure is passed in the actual parameters window, and then use the formal parameter to receive
formal parameter undefined
Because browsers with lower versions of IE can successfully assign values to undefined, so in order to ensure the purity of undefined, give it a formal parameter position without actual parameters, ensuring that it must be undefined
jQuery parameter selector
##selector can be a pair of tags, which can be id, class, descendant , descendants, etc., can be jQuery objects,
jQuery prototype object assignment
Conveniently extend jQuery’s prototype method
return Instantiate prototype method init
In fact, it is so that we don’t need new $() every time we use $;
Why does jQuery need to new its own prototype? As for the method, because if you don’t new your own, you will need to new other functions to return, so why not use your own
jQuery prototype object to assign to jQuery The prototype of the prototype method init
Because every time a method is extended to the jQuery prototype internally, init will also have this method. Isn’t it cool? Init has So, is there a jQuery object that comes out of $()?
##After being exposed to the window, jQuery and $ can be used directly globally -
As for why there is $, because it is short, of course you can also use jQuery() every time
## Royal Selector-Sizzle
Sizzle is also the foundation of jQuery. Of course, you can also use Sizzle alone
As mentioned above, $(selector) The parameter selector can be id, class, descendant, descendant, etc., or it can be a jQuery object. So how can we get the jQuery object we want with just $ every time? Yes, It is because of Sizzle that Sizzle encapsulates methods for obtaining various DOM objects and packages them into jQuery objects
Browser capability test
There is a support object inside Sizzle. The support object stores the results of regular test browser capabilities
##Use universal compatibility solutions for selectors with capability issues (complicated judgment code)
Regular
Regular expressions are still used a lot in jQuery. The use of regular expressions can greatly improve our data processing efficiency
judge
列如可能是个html标签,那么直接create一个selector标签的DOM对象包装成jQuery对象return出去
列如可能是个id名、类名、标签名等等,那么直接通过Sizzle获取到DOM对象包装成jQuery对象return出去
判断是在init内部判断selector的类型,
包装
我已经说了很多次的包装了,没错,jQuery对象其实也是个伪数组,这也是它的设计巧妙之处,因为用数组存储数据方便我们去进行更多的数据处理,比如 $("p").css("color": "red") ,那么jQuery会自动帮我们隐式迭代、再给页面上所有p包含的文字颜色设置为red,简单粗暴的一行代码搞定简直是程序猿的最爱
对外扩展-extend
jQuery核心的结构处理完毕之后基本上就可以对外使用了,但是我们知道我们是可以基于jQuery来实现插件的,包括jQuery自己可扩展性也必须要求他要对外提供一个接口方便进行二次开发,所以有了extend方法
简单的extend就是混入,列子:
<span style="font-size: 14px;">function extend(obj) {<br> var k;<br> for(k in obj) {<br> this[k] = obj[k];<br> }<br> }<br><br> Baiya.extend = extend;<br> Baiya.fn.extend = extend;<br></span>
对静态方法的和实例方法的扩展都要有,比如each方法,可以$.each来使用,也可以是$("p").each来使用
之后jQuery一些方法都是基于extend来扩展的,当然我们自己也可以基于jQuery扩展方法
DOM操作
DOM操作也是jQuery的一大特点,因为它太好用了,包含了我们所能想到的所有使用场景,完善了增删查改常用的方法
jQuery获取和设置类的方法如html()/css()/val()等等这些传参是设置值不传参是获取值
##链式编程
jQuery是支持链式编程的,只要你想你就可以一行代码写完所有的功能,这是怎么做到的呢
每一个改变原型链的方法都会把当前的this对象保存成他自己的属性,然后可以调用end方法找到上一级链从而方便我们可以进行链式操作
事件操作
jQuery的事件操作一般可以通过click类(mouseover/mouseleave等等)和on来使用,但是click类的实现是调用on的
on的实现是对原生的onclick类的处理,因为相同的原生的事件在同一个DOM对象上只能被绑定一次,如果再次绑定会覆盖掉上一次的,所以jQuery帮我们封装了事件的存储,把相同的事件分成一个数组存储在一个对象里面,然后对数组进行遍历,依次调用数组里存储的每个方法
on实现之后会把所有的事件处理字符串处理一下用on来改造一下,如下:
<span style="font-size: 14px;">Baiya.each(("onclick,onmousedown,onmouseenter,onmouseleave," +<br> "onmousemove,onmouseout,onmouseover,onmouseup,onfocus," +<br> "onmousewheel,onkeydown,onkeypress,onkeyup,onblur").split(","), function (i, v) {<br> var event = v.slice(2);<br> Baiya.fn[event] = function (callback) {<br> return this.on(event, callback);<br> }<br> });<br></span>
属性操作
jQuery也提供给了我们方便的属性操作,底层就是对原生方法的包装,处理兼容性问题,如果jQuery不对IE浏览器的兼容处理的话,那么它的代码量可能会缩一半,当然锅不能全部甩给IE,比如innerText方法火狐是不支持的,但是支持textContent方法,所以jQuery会尽可能的处理这种浏览器带来的差异
样式操作
基本思想如上
Ajax操作
Ajax可以说是前端的跨越性进步,毫不夸张的说如果没有Ajax的发展,那么今天的前端可能不叫前端,可能是美工……
Ajax是什么?
在我的理解来看Ajax就是一个方法,这个方法遵循着http协议的规范,我们可以使用这个方法来向服务器请求少量的数据,有了数据之后我们就可以操作DOM来达到局部更新网页的目的,这是一个非常酷的事情
jQuery的Ajax是基于XMLHttpRequest的封装,当然了他也有兼容性问题,具体的封装见我之前的文章 简单的ajax封装
具体就是区别get和post请求的区别,get请求的传参是直接拼接在url结尾,而post请求需要在send()里面传递,并且post请求还要设置请求头setRequestHeader("content-type", "application/x-www-form-urlencoded")
请求后对json或者text或者xml的数据进行处理就可以渲染到页面了
提到Ajax就不得不提到跨域了
跨域简单的来说限制了非同源(ip/域名/端口/协议)的数据交互,当然这肯定是极好的,因为如果不限制那么你的网页别人也可以操作是不是很恐怖
但是有些情况下我们需要调用别人的服务器数据,而且别人也愿意怎么办呢,程序员是很聪明的,html标签中img,script,link等一些带有src属性的标签是可以请求外部资源的,img和link得到的数据是不可用的,只有script标签请求的数据我们可以通过函数来接收,函数的参数传递可以是任何类型,所以创建一个函数,来接收,参数就是请求到的数据,而对方的数据也要用该函数来调用就可以实现跨域了
简单封装jsonp实现
<span style="font-size: 14px;">// url是请求的接口<br>// params是传递的参数<br>// fn是回调函数<br>function jsonp(url, params, fn){<br> // cbName实现给url加上哈希,防止同一个地址请求出现缓存<br> var cbName = `jsonp_${(Math.random() * Math.random()).toString().substr(2)}`;<br> window[cbName] = function (data) {<br> fn(data);<br> // 获取数据后移除script标签<br> window.document.body.removeChild(scriptElement);<br> };<br><br> // 组合最终请求的url地址<br> var querystring = '';<br> for (var key in params) {<br> querystring += `${key}=${params[key]}&`;<br> }<br> // 告诉服务端我的回调叫什么<br> querystring += `callback=${cbName}`;<br><br> url = `${url}?${querystring}`;<br><br> // 创建一个script标签,并将src设置为url地址<br> var scriptElement = window.document.createElement('script');<br> scriptElement.src = url;<br> // appendChild(执行)<br> window.document.body.appendChild(scriptElement);<br> }<br></span>
Animate
很抱歉的是jQuery的动画源码我并没有阅读,但是我自己封装了一个动画函数,之后的源码阅读会补上的
封装的代码
<span style="font-size: 14px;">// element设置动画的DOM对象<br>// attrs设置动画的属性 object<br>// fn是回调函数<br>function animate(element, attrs, fn) {<br> //清除定时器<br> if(element.timerId) {<br> clearInterval(element.timerId);<br> }<br> element.timerId = setInterval(function () {<br> //设置开关<br> var stop = true;<br> //遍历attrs对象,获取所有属性<br> for(var k in attrs) {<br> //获取样式属性 对应的目标值<br> var target = parseInt(attrs[k]);<br> var current = 0;<br> var step = 0;<br> //判断是否是要修改透明度的属性<br> if(k === "opacity") {<br> current = parseFloat( getStyle(element, k)) * 100 || 0;<br> target = target * 100;<br> step = (target - current) / 10;<br> step = step > 0 ? Math.ceil(step) : Math.floor(step);<br> current += step;<br> element.style[k] = current / 100;<br> //兼容ie<br> element.style["filter"] = "alpha(opacity="+ current +")";<br> }else if(k === "zIndex") {<br> element.style[k] = target;<br> } else {<br> //获取任意样式属性的值,如果转换数字失败,返回为0<br> current = parseInt(getStyle(element, k)) || 0;<br> step = (target - current) / 10;<br> console.log("current:" + current + " step:" + step);<br> step = step > 0 ? Math.ceil(step) : Math.floor(step);<br> current += step;<br> //设置任意样式属性的值<br> element.style[k] = current + "px";<br> }<br> if(step !== 0) {<br> //如果有一个属性的值没有到达target ,设置为false<br> stop = false;<br> }<br><br> }<br> //如果所有属性值都到达target 停止定时器<br> if(stop) {<br> clearInterval(element.timerId);<br> //动画执行完毕 回调函数<br> if(fn) {<br> fn();<br> }<br> }<br> },30);<br> }<br><br> //获取计算后的样式的值<br> function getStyle(element, attr) {<br> //能力检测<br> if(window.getComputedStyle) {<br> return window.getComputedStyle(element, null)[attr];<br> }else{<br> return element.currentStyle[attr];<br> }<br> }<br></span>
以上内容就是 jQuery 开发经验库的分享,希望能帮助到大家。
相关推荐:
The above is the detailed content of jQuery development experience library. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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



This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

"Understanding VSCode: What is this tool used for?" 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
