继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

jQuery tips and tricks - 1

零基础h5前端入门培训
关注TA
已关注
手记 301
粉丝 37
获赞 253

There are many
articles about jQuery tips and tricks on the internet.

I am very happy to have so many resources for reference, and i will make my own
examples in order to learn these tips and tricks for a better work effective.

1. Get the DOM elements from a jQuery object

    $("div")[0];
    $("div").get(0);
    $("div").get()[0];

Note:get() returns all matched DOM elements in an array.

Get the tag name of a DOM node:

    $("body")[0].tagName.toLowerCase() === "body"; // true
    $("div").click(function() {
        this.tagName.toLowerCase() === "div"; //true
    });

2. Whether a jQuery object has DOM elements

    if($("div").length) {
        // there is at least one div DOM element in the page
    }
    // The following code snipppets do the same thing:
    // if($("div").size()) ...
    // if($("div")[0]) ...
    // if($("div").get(0)) ...

Beware of the this error decision:

    // if($("div")) ....

beacuse:

    !!$("div") // true
    !!$("no_thus_tag") // true
    !!$({}) // true

3. Find the index of an element

    <ul class="menu">
        <li>menu 1</li>
        <li>menu 2</li>
        <li>menu 3</li>
    </ul>
    $("ul.menu li").click(function() {
        // Find the index of this li node
        $(this).parent().find("li").index(this); // "menu 1" -> 0
    });

Or it can be write in a more effective way:

    var lis = $("ul.menu li");
    lis.click(function() {
        lis.index(this); // "menu 3" -> 2
    });

4. Bind event to ANY jQuery object, NOT only jQuery DOM object

In Athena client-side JavaScript framework, we need a global event publish&subscribe
mechanism:

    (function() {

        function eventNode() {
            var node = $("#_wbx_event");
            if (node.length === 0) {
                node = $("<div />").attr("id", "_wbx_event").appendTo("body");
            }
            return node;
        }

        $.wbx = $.wbx || {};
        $.wbx.util = {
            trigger: function() {
                var node = eventNode();
                node.trigger.apply(node, arguments);
            },

            bind: function() {
                var node = eventNode();
                node.bind.apply(node, arguments);
            }
        };

    })();

This code can also be wrote like this:

    (function() {

        var eventObj = $({});

        $.wbx = $.wbx || {};
        $.wbx.util = {
            trigger: function() {
                eventObj.trigger.apply(eventObj, arguments);
            },

            bind: function() {
                eventObj.bind.apply(eventObj, arguments);
            }
        };

    })();

Test code:

    $(function() {

        $.wbx.util.bind("custom_event_1", function(e, data) {
            // trigger custom_event_1 target_body
            alert("trigger custom_event_1 " + data);
        });

        $("body").click(function() {
            $.wbx.util.trigger("custom_event_1", ["target_body"]);
        });

    });

5. $.fn is just a shortcut of $.prototype

In fact, $ is a function and $.prototype is used to define functions that extend
the jQuery objects.

In the beginning, i was confused with the principle of jQuery:

If $ is a function, and we define a plugin like this $.prototype.plugin1 = function()
{};

It’s likely we should invoke our plugin this way:

    (new $("div")).plugin1();

But actually invocation:

    $("div").plugin1();

After review the jQuery source code, i understood the way jQuery works.

And this is a step by step tutorial to demostrate how can jQuery achieve this:

STEP 1:

    function W() {
    }
    W.prototype.plugin1 = function() {
        alert("plugin1");
    };
    (new W()).plugin1();

STEP 2:

    function W() {
        return new Q();
    }
    function Q() {
    }
    Q.prototype.plugin1 = function() {
        alert("plugin1");
    };
    W().plugin1();

STEP 3:

    function W() {
        return new Q();
    }
    function Q() {
    }
    Q.prototype = W.prototype;

    W.prototype.plugin1 = function() {
        alert("plugin1");
    };
    W().plugin1();

STEP 4:

    function W() {
        return new W.prototype.init();
    }
    W.prototype = {
        init: function() {
        }
    };
    W.prototype.init.prototype = W.prototype;

    W.prototype.plugin1 = function() {
        alert("plugin1");
    };
    W().plugin1();

STEP 5: The following is the way jQuery implement:

    jQuery = function(selector, context) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init(selector, context);
    };

    jQuery.fn = jQuery.prototype = {
        init: function(selector, context) {
            var result = [];    // omit the implemention details
            return this.setArray(result);
        },
        setArray: function(elems) {
            // Resetting the length to 0, then using the native Array push
            // is a super-fast way to populate an object with array-like properties
            this.length = 0;
            Array.prototype.push.apply(this, elems);
            return this;
        }
    };
    // Give the init function the jQuery prototype for later instantiation
    jQuery.fn.init.prototype = jQuery.fn;
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP