一天一点新东西-jq插件写法


1.通过$.extend()来扩展jQuery

$.extend({
test: function () {
//函数方法
}
})

直接通过$调用函数
$.test()

2.通过$.fn 向jQuery添加新的方法

index.js

;(function ($,window,document,undefined) {//分号是好习惯
var methods={
init: function () {
return this.each(function () {
//相应方法
})
},
otherfunc: function () {

}
}
$.fn.myPlugin = function(param) {
//this是被选中的jq对象元素
console.log(this.text());
//if ( methods[method] ) {
// return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
//} else if ( typeof method === 'object' || ! method ) {
// return methods.init.apply( this, arguments );
//} else {
// $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
//}
return this.each(function () {
//this被选中的dom对象元素
var $this=$(this);
$this.text(param);
});


}
})(jQuery,window,document)

index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script src="index.js"></script>
<script>
$(function(){
$('.nnn').myPlugin('5');
})
</script>
</head>
<body>
<div class="nnn">1</div>
<p class="nnn">2</p>
</body>
</html>

注意调用插件方法$().myPlugin()最好在dom加载完成之后。

			

                        优质内容筛选与推荐>>
1、Maven: 每次更新Maven Project ,JAVA 版本都变为1.5
2、过拟合与欠拟合
3、android studio学习:增加android studio内存空间大小
4、20165226 预备作业3 Linux安装及学习
5、服务器如何开机后启动一个程序


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号