jQuery插件我们用的很多,也很好用,我在生产任务中也碰到了很多冗余代码,我就想把他们封装起来,一直百思不得其解,现在捅破了这个窗户纸,分享给大家。
jQuery对象封装其实很简单
首先大家对prototype这个方法应该不陌生,
Array.prototype.say=function(str){
console.log(str);
}
这样就给数组增加了一个新的方法,用的时候只要new出来一个对象,然后使用这个方法就行了:
var arr= new Array();
arr.say("Hello World!");
同理====》
强大的jQuery也支持自定义插件(丰富jQuery方法)
jQuery自定义方法是这么玩的===》
jQuery.prototype.say=function(str){
console.log(str);
}
这么冗余的写法当然也可以简化:
$.fn.say=function(str){
console.log(str);
}
e.g:
$("div").say("哈哈哈哈");
在方法体里可以用this来指代当前被选中的元素:
$.fn.bgColor=function(){
this.css("backgroundColor","red");
}
$("div").bgColor();