有时候在写一些演习或许小的项目时,我们能够只想用用jquery的$
选择器,好用的hide
、show
等等一些基本的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对象作为参数,在组织函数的原型对象上就能够绑定种种事宜,比方on
,show
以至是jquery中没有的css
等等,假如想完成链式挪用,即返回this对象即可。应用querySelector
来封装$
,上面的示例只是简朴的封装,并没有完成兼容性的写法,比方on
关于IE的处置惩罚。事宜侦听能够越发雄厚:通用的事宜侦听器只是关于jquery的完成道理举行的简朴的模仿。
简朴的封装一下,就能够兴奋的写东西啦。