JQuery 自定義函數
1、前言
像我這樣沒有經過系統學習前端的同學,對jquery的理解估計還只是停留在基本的使用上,在這裏抽出時間梳理下,jquery自定義方法,以及基本的調用,畢竟在網上用了那麼多jquery第三方插件,卻還不知道怎麼定義的。
2、自定義函數及其使用示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="button" value="按鈕" id="myBtn">
</body>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
//$("button").myFuncOne();
$("button").myFuncFour();
$.myFuncTwo();
})
/**
* jQuery中添加自定義或函數方法1,如$.fn.extend({'aa':function(){}})或jQuery.fn.aa=function(){},這種調用時就得這樣,$("#**").aa()
*/
jQuery.fn.myFuncOne=function(){
alert("我的自定義jquery方法1");
}
jQuery.fn.extend({
'myFuncFour':function(){
alert("我的自定義jquery方法4");
}
})
/**
* jQuery中添加自定義或函數方法2,如$.extend({'aa':function(){}}),這種調用時就是這樣$.aa()
*/
jQuery.extend({
'myFuncTwo':function(){
alert("我的自定義jquery方法2");
}
})
/**
* jQuery中添加自定義或函數方法3,如 $.myFuncThree('/post/getsecurejsonpost',{}, function(data) {});
*/
$.myFuncThree = function(url, data, successCB){
alert("我的自定義jquery方法3,參數:"+url);
if(successCB){//回調
successCB(url);
}else{
alert("沒有回調");
}
}
function myFuncThreeCB(url){
alert("myFuncThreeCB+"+url)
}
/*
* 測試按鈕
*/
$("#myBtn").click(function(){
$("#myBtn").myFuncOne();
$("#myBtn").myFuncFour();
$().myFuncTwo();
$.myFuncThree("www.baidu.com",'hello',myFuncThreeCB);
$.myFuncThree("www.baidu.com",'hello');
})
</script>
</html>