您的位置:首页 > Web前端 > JQuery

jQuery扩展两类函数(对象调用,静态调用)

2014-05-14 18:35 459 查看
作者:zccst

先看小例子:

$(function(){
//扩展方式1-通过对新调用
$.fn.each1=function(){
console.log("hehehehe$.fn.func");
}
$.fn.extend({
"each2":function(){
console.log("second method!,$.fn.extend(each2:function(){})");
}
});
//扩展方式2-静态调用
$.extend({
"each3":function(){
console.log("hahah,$.extend(each3:function(){})");
}
});
$("button").click(function(){
console.log($(".name").val());
$(this).each1();//通过对象调用
$(this).each2();//通过对象调用
$.each3();//扩展方式2-静态调用
});
});

名字:<input class="name" type="text" />
<button>提交</button>


方法一:对象调用
jQuery.fn.setApDiv=function () {
//apDiv浮动层显示位置居中控制
var wheight=$(window).height();
var wwidth=$(window).width();
var apHeight=wheight-$("#apDiv").height();
var apWidth=wwidth-$("#apDiv").width();
$("#apDiv").css("top",apHeight/2);
$("#apDiv").css("left",apWidth/2);
}

调用方法:$("#apDiv").setApDiv();

--------------------------------------------------------------------------------
方法二:静态调用
//jQuery 应用扩展
jQuery.extend({
// 设置 apDiv
setApDiv:function () {
//apDiv浮动层显示位置居中控制
var wheight=$(window).height();
var wwidth=$(window).width();
var apHeight=wheight-$("#apDiv").height();
var apWidth=wwidth-$("#apDiv").width();
$("#apDiv").css("top",apHeight/2);
$("#apDiv").css("left",apWidth/2);
}
});
调用方法:$.setApDiv();

总结 一种如$.extend({'aa':function(){}}),这种调用时就是这样$.aa(),另一种如$.fn.extend({'aa':function(){}}),这种调用时就得这样,$(this).aa()

--------------------------------------------------------------------------------
方法三:

$.postJSON = function(url, data, callback) {
$.post(url, data, callback, "json");
};
调用方法:$.postJSON('/post/getsecurejsonpost',{}, function(data) {});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐