Home  >  Article  >  Web Front-end  >  Secrets about jQuery

Secrets about jQuery

小云云
小云云Original
2017-11-25 09:37:241413browse

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)

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;

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);
        }
    });

属性操作

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);
       }

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];
        }
    }

以上讲述这么多来分析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:
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