博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个最简单的类JQuery封装
阅读量:7256 次
发布时间:2019-06-29

本文共 1265 字,大约阅读时间需要 4 分钟。

有时候在写一些练习或者小的项目时,我们可能只想用用jquery的$选择器,好用的hideshow等等一些基础的API,那么我们又不想因为这么几个API来引入一个jquery的js文件,那么自己封装一个最好不过了。

(function (document) {    function DomObject(dom) {        this.dom = dom;    }    function $(selector) {        return new DomObject(document.querySelector(selector));    }    DomObject.prototype.get = function () {        return this.dom;    }    DomObject.prototype.on = function(eventName, eventHandler) {        this.get().addEventListener(eventName, eventHandler);        return this;    }    DomObject.prototype.css = function(styleKey, styleValue) {        this.get().style[styleKey] = styleValue;        return this;    };    DomObject.prototype.hide = function() {        this.get().style.display = 'none';        return this;    };    DomObject.prototype.show = function() {        this.get().style.display = 'block';        return this;    }    $('.main #btn-hide').on('click', function() {        $('h2').hide();    });    $('.container #btn-show').on('click', function() {        $('h2').show().css('color','red');    });})(document);

首先创建一个构造函数,传入一个dom对象作为参数,在构造函数的原型对象上就可以绑定各种事件,比如onshow甚至是jquery中没有的css等等,如果想实现链式调用,即返回this对象即可。利用querySelector来封装$,上面的示例只是简单的封装,并没有实现兼容性的写法,比如on对于IE的处理。事件侦听可以更加丰富:只是对于jquery的实现原理进行的简单的模拟。

简单的封装一下,就可以愉快的写东西啦。

转载地址:http://jcvdm.baihongyu.com/

你可能感兴趣的文章