JavaScript插件创建

Ane*_*esh 4 javascript plugins

如何创建一个纯JavaScript(不使用任何库)插件,如下所示:

document.getElementById('id').myPlugin();
Run Code Online (Sandbox Code Playgroud)

喜欢jQuery吗?

Jam*_*mes 5

您可以创建自己的包装器(类似于jQuery),并通过直接扩展DOM来绕开所有讨论的问题。

myWrapper = (function(){

    function NodeList(elems) {

        this.length = 0;
        this.merge(this, elems.nodeType ? [elems] : elems);

    }

    function myWrapper(elems) {
        return new NodeList(elems);
    }

    myWrapper.NodeList = NodeList;

    NodeList.prototype = {
        merge: function(first, second) {

            var i = first.length, j = 0;

            for (var l = second.length; j < l; ++j) {
                first[i++] = second[j];
            }

            first.length = i;

            return first;

        },
        each: function(fn) {

            for (var i = -1, l = this.length; ++i < l;) {
                fn.call(this[i], this[i], i, l, this);
            }

            return this;

        }
    };

    return myWrapper;

})();
Run Code Online (Sandbox Code Playgroud)

您可以添加自己的方法,如下所示:

myWrapper.NodeList.prototype.myPlugin = function() {
    return this.each(function(){
        // Do something with 'this' (the element)
    });
};
Run Code Online (Sandbox Code Playgroud)

用法:

myWrapper(document.getElementById('id')).myPlugin();
Run Code Online (Sandbox Code Playgroud)