有时候在写一些练习或者小的项目时,咱们可能只想用用jquery的$
选择器,好用的hide
、show
等等一些基础的API,那么咱们又不想由于这么几个API来引入一个jquery的js文件,那么本身封装一个最好不过了。javascript
(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对象做为参数,在构造函数的原型对象上就能够绑定各类事件,好比on
,show
甚至是jquery中没有的css
等等,若是想实现链式调用,即返回this对象便可。利用querySelector
来封装$
,上面的示例只是简单的封装,并无实现兼容性的写法,好比on
对于IE的处理。事件侦听能够更加丰富:通用的事件侦听器只是对于jquery的实现原理进行的简单的模拟。css
简单的封装一下,就能够愉快的写东西啦。java