Home Web Front-end JS Tutorial Secrets about jQuery

Secrets about jQuery

Nov 25, 2017 am 09:37 AM

What are the characteristics of jQuery? Dynamic special effects, AJAX, extension through plug-ins, convenient tools - such as browser version detection, progressive enhancement, chain call, multi-browser support, support Internet Explorer6.0+, Opera9.0+, Firefox2+, Safari2.0+ , Chrome1.0+ (support for Internet Explorer6,7,8 was canceled in 2.0.0).

Sometimes I wonder why jQuery can directly $ operate, it can have more convenient DOM operations than native js, and you can directly chain operations as long as you want

Core Framework

Revealing the jQuery core code with more than 10,000 lines of code:

(function(window, undefined) {function jQuery(selector){return new jQuery.fn.init(selector)
}
jQuery.fn = jQuery.prototype = {
init: function () {
}
}
jQuery.fn.init.prototype = jQuery.fn;window.jQuery = window.$ = jQuery;
})(window)
Copy after login

Closure structure passing parameter window

Reduce the query time of each internal reference to window

It is convenient to compress the code

The closure structure is passed in the actual parameter window, and then the formal parameter is used to receive it

The formal parameter is undefined

Because browsers with lower versions of IE can assign a value to undefined Success, 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 labels, you can It is an id, class, descendant, descendant, etc. It can be a jQuery object,

jQuery prototype object assignment

Conveniently extend jQuery’s prototype method

return Instantiate prototype method init

In fact, it is so that every time we use $, we don’t need new $();

Why does jQuery need to new its own prototype method? Because if you don’t new your own, you will need to new other functions to return. Then why not use your own

The jQuery prototype object is assigned to the prototype of the jQuery prototype method init

Because every time a method init is extended to the jQuery prototype internally, init will also have this method, isn't it cool? Cool, is there a jQuery object that comes out of $() after init?

Exposes the available member jQuery to the window, $

After exposing it to the window, jQuery can be used directly globally. And $

As for why there is $, it’s because it’s short. Of course, you can also use jQuery() every time

The royal selector-Sizzle

Sizzle is also jQuery Basically, of course, you can also use Sizzle alone

As mentioned above, the parameter selector of $(selector) can be id, class, descendant, descendant, etc., and can be a jQuery object, so we can use $ each time How can we get the jQuery objects we want all the time? That’s right, it’s because of Sizzle. Sizzle encapsulates methods for obtaining various DOM objects and packages them into jQuery objects

Browser capability test

There is a support object inside Sizzle, and the support object stores the results of the regular test browser capability

Use a universal compatibility solution for selectors with capability problems (complicated Judgment code)

Regular expressions

Regular expressions are still commonly used in jQuery, and the use of regular expressions can greatly improve our data processing efficiency

Judgment

The column may be an html tag, then directly create a DOM object of the selector tag and wrap it into a jQuery object and return it.

The column may be an id name, class name, tag name, etc. Then directly obtain the DOM object through Sizzle and package it into a jQuery object and return it out.

The judgment is to determine the type of selector inside init,

Packaging

I have said it many times Wrapped, yes, the jQuery object is actually a pseudo-array. This is also the ingenuity of its design, because using arrays to store data facilitates us to perform more data processing, such as $("div").css("color ": "red"), then jQuery will automatically help us iterate implicitly, and then set the text color contained in all divs on the page to red. It can be done with a simple and crude line of code, which is simply a programmer's favorite

External extension-extend

After the jQuery core structure is processed, it can basically be used externally, but we know that we can implement plug-ins based on jQuery, including jQuery's own scalability, which must also be required for external use. Provide an interface to facilitate secondary development, so there is an extend method

A simple extend is to mix in, example:

function extend(obj) {        var k;        for(k in obj) {            this[k] = obj[k];
        }
    }
    Baiya.extend = extend;
    Baiya.fn.extend = extend;
Copy after login

There must be extensions for static methods and instance methods, such as each Method, you can use $.each, or you can use $("div").each

After that, some jQuery methods are extended based on extend. Of course, we can also extend methods based on jQuery

DOM operation

DOM operation is also a major feature of jQuery, because it is so easy to use, includes all usage scenarios we can think of, and improves the commonly used methods of adding, deleting, checking and modifying

jQuery’s methods of getting and setting classes, such as html()/css()/val(), etc. These parameters are set to set the value. If not, the value is obtained.

##Chain programming

jQuery supports chain programming. As long as you want, you can write all the functions in one line of code. How is this done?

Every method that changes the prototype chain will change the current This object is saved as its own attribute, and then the end method can be called to find the upper level chain so that we can perform chain operations

Event operations

JQuery's event operations can generally be done through the click class (mouseover/mouseleave, etc.) and on are used, but the implementation of the click class is to call on

on的实现是对原生的onclick类的处理,因为相同的原生的事件在同一个DOM对象上只能被绑定一次,如果再次绑定会覆盖掉上一次的,所以jQuery帮我们封装了事件的存储,把相同的事件分成一个数组存储在一个对象里面,然后对数组进行遍历,依次调用数组里存储的每个方法

on实现之后会把所有的事件处理字符串处理一下用on来改造一下,如下:

Baiya.each(("onclick,onmousedown,onmouseenter,onmouseleave," +    "onmousemove,onmouseout,onmouseover,onmouseup,onfocus," +    "onmousewheel,
onkeydown,onkeypress,onkeyup,onblur").split(","),     function (i, v) {        var event = v.slice(2);
        Baiya.fn[event] = function (callback) {            return this.on(event, callback);
        }
    });
Copy after login

属性操作

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实现

// url是请求的接口// params是传递的参数// fn是回调函数function jsonp(url, params, fn){	// cbName实现给url加上哈希,防止同一个地址请求出现缓存
           var cbName = `jsonp_${(Math.random() * Math.random()).toString().substr(2)}`;            window[cbName] = function (data) {
               fn(data);                // 获取数据后移除script标签
               window.document.body.removeChild(scriptElement);
           };            // 组合最终请求的url地址
           var querystring = '';            for (var key in params) {
               querystring += `${key}=${params[key]}&`;
           }            // 告诉服务端我的回调叫什么
           querystring += `callback=${cbName}`;

           url = `${url}?${querystring}`;            // 创建一个script标签,并将src设置为url地址
           var scriptElement = window.document.createElement('script');
           scriptElement.src = url;            // appendChild(执行)
           window.document.body.appendChild(scriptElement);
       }
Copy after login

Animate

封装的代码

// element设置动画的DOM对象// attrs设置动画的属性object// fn是回调函数function animate(element, attrs, fn) {        //清除定时器
        if(element.timerId) {
            clearInterval(element.timerId);
        }
        element.timerId = setInterval(function () {            //设置开关
            var stop = true;            //遍历attrs对象,获取所有属性
            for(var k in attrs) {                //获取样式属性 对应的目标值
                var target = parseInt(attrs[k]);                var current = 0;                var step = 0;                //判断是否是要修改透明度的属性
                if(k === "opacity") {
                    current = parseFloat( getStyle(element, k)) * 100 || 0;
                    target = target * 100;
                    step = (target - current) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    current += step;
                    element.style[k] = current / 100;                    //兼容ie
                    element.style["filter"] = "alpha(opacity="+  current +")";
                }else if(k === "zIndex") {
                    element.style[k] = target;
                } else {                    //获取任意样式属性的值,如果转换数字失败,返回为0
                    current = parseInt(getStyle(element, k)) || 0;
                    step = (target - current) / 10;                    console.log("current:" + current + "  step:" + step);
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    current += step;                    //设置任意样式属性的值
                    element.style[k] = current + "px";
                }                if(step !== 0) {                    //如果有一个属性的值没有到达target  ,设置为false
                    stop = false;
                }
            }            //如果所有属性值都到达target  停止定时器
            if(stop) {
                clearInterval(element.timerId);                //动画执行完毕  回调函数
                if(fn) {
                    fn();
                }
            }
        },30);
    }    //获取计算后的样式的值
    function getStyle(element, attr) {        //能力检测
        if(window.getComputedStyle) {            return window.getComputedStyle(element, null)[attr];
        }else{            return element.currentStyle[attr];
        }
    }
Copy after login

以上讲述这么多来分析jQuery,我相信大家也一定对jQuery有了新的认识和认知,希望大家能有收获。

相关推荐:

如何高效使用jquery

JS和JQUERY有什么区别

jq源码中绑在$,jQuery上面的方法

The above is the detailed content of Secrets about jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Revealing the secrets of canvas properties Revealing the secrets of canvas properties Jan 17, 2024 am 10:08 AM

To explore the secrets of the canvas attribute, you need specific code examples. Canvas is a very powerful graphics drawing tool in HTML5. Through it, we can easily draw complex graphics, dynamic effects, games, etc. in web pages. However, in order to use it, we must be familiar with the related properties and methods of Canvas and master how to use them. In this article, we will explore some of the core properties of Canvas and provide specific code examples to help readers better understand how these properties should be used.

Decrypting the matplotlib color table: revealing the story behind the colors Decrypting the matplotlib color table: revealing the story behind the colors Jan 09, 2024 am 11:38 AM

Detailed explanation of matplotlib color table: Revealing the secrets behind colors Introduction: As one of the most commonly used data visualization tools in Python, matplotlib has powerful drawing functions and rich color tables. This article will introduce the color table in matplotlib and explore the secrets behind colors. We will delve into the color tables commonly used in matplotlib and give specific code examples. 1. The color table in Matplotlib represents the color in matplotlib.

Revealing the secrets behind the Realme mobile phone brand Revealing the secrets behind the Realme mobile phone brand Mar 24, 2024 am 08:57 AM

As a first-line mobile phone brand, Realme mobile phone brand has always attracted the attention and attention of consumers. However, as we all know, behind every successful brand there is an unknown journey and story. This article will reveal the secrets behind the Realme mobile phone brand and conduct an in-depth discussion from the origin, development process and market strategy of the brand. The real mobile phone brand originates from OPPO Electronics Corp., a Chinese mobile communications equipment company, and was officially launched in 2018, adhering to the brand concept of "real mobile phone". True self brand is committed to

The reason why Linux is rock stable: Secrets you don't know The reason why Linux is rock stable: Secrets you don't know Mar 14, 2024 pm 02:33 PM

As an open source operating system, Linux system has always been known for its stability and reliability, and is widely used in servers, embedded devices and other fields. So, how exactly does a Linux system remain rock solid? What secrets are hidden in this? This article will reveal the reasons for Linux system stability and reveal these secrets through specific code examples. 1. Open source code Linux system is an open source project, and its source code is open to the public and anyone can view and modify it.

The secret behind the Golang icon: Is it a dog? The secret behind the Golang icon: Is it a dog? Mar 06, 2024 pm 05:54 PM

The secret behind the Golang icon: Is it a dog? Golang, the Go language, is an open source programming language developed by Google. It has efficient concurrent processing capabilities, concise syntax, and fast compilation speed, so it has received widespread attention and use. The official logo of Golang has also attracted much attention. Its design is simple and layered, which makes people think of a mysterious animal. What kind of secret is hidden behind this logo? Some people guess that this logo is actually a picture of a dog, so this guess

Integrated caching: the secret to PHP's high performance Integrated caching: the secret to PHP's high performance Jun 03, 2023 pm 09:31 PM

PHP is a very popular programming language that is easy to learn, powerful and highly flexible. However, when processing large amounts of data and high concurrent requests, PHP's performance issues often become bottlenecks that limit application performance. To solve this problem, developers often use caching techniques to improve the performance and scalability of PHP applications. Caching is a technique for saving data in memory so that applications can quickly obtain already calculated results without having to calculate them again. In PHP, caching technology

Demystifying CSS Property Selectors Demystifying CSS Property Selectors Jan 13, 2024 am 11:58 AM

Secrets of CSS Attribute Selectors Revealed CSS attribute selectors are a very useful and powerful tool that allow us to select and style specific elements by their attribute values. These attribute selectors can match and select based on the element's attribute value, where the attribute value appears, and specific characters in the attribute value. This article will reveal the secrets of CSS attribute selectors through specific code examples. First, let's learn about some basic CSS attribute selectors. The most common attribute selector is "[attribute]

Taobao's secret weapon: Go language technology revealed Taobao's secret weapon: Go language technology revealed Feb 26, 2024 pm 02:48 PM

Taobao is China's largest online shopping platform, with hundreds of millions of users purchasing goods every day. In supporting the operation of such a huge platform, technology plays a vital role. In recent years, with the popularity of Go language in the Internet field, some people have begun to speculate whether Taobao's success is related to Go language. This article will start from a technical perspective and specifically explore the application of Go language in Taobao and the reasons why it may become Taobao's secret weapon. First, let’s analyze the technical challenges Taobao faces. as a huge

See all articles