案例引用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery插件的四种方法案例</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<!-- <script type="text/javascript" src="jquery-tableColor-1.1.js"></script> -->
<script type="text/javascript">
//第一种,对jQuery自身的方法库进行扩展,在使用的时候$.methodName()来调用
/*
$.extend({
handleTableUI:function(table) {
var thisTable = $("#" + table);
$(thisTable).find('tr').hover(function() {
$(this).css({
color: "#ff0011",
background: "red"
});
}, function () {
$(this).css({
color:"#000000",
background:"yellow"
})
});
}
});
//使用方法
$(document).ready(function() {
$.handleTableUI('table');
});
//第二种写法,对html标记或者页面元素进行扩展,使用方法$(#id).methodName();
//JQuery是框架里面提供的一个对象,使用的时候必须引入jquery框架的代码
(function ($) {
//$.fn 是jquery的一个属性,通过扩展它来实现插件的封装
$.fn.setTableUI = function (options) {
var defaults = {
color:'white',
background:'blue'
};
//把传过来的参数与默认的参数合并,如果传进来的参数修改默认参数的值以传进来的为准
options = $.extend(defaults, options);
//this.each 是遍历获取到dom对象的数组,就是用法里面的$("#id")获取到的
return this.each(function(index) {
var thisTable = this;
$(thisTable).find('tr').hover(function() {
$(this).css({
color:options.color,
background:options.background
});
}, function() {
$(this).css({
color:'black',
background:'white',
});
});
});
}
})(jQuery);
//调用的时候先获取dom对象,然后采用相对应的方法
$(function() {
$("#table").setTableUI({background:'green'});
});
//第三种写法,不需要显示调用,直接全局生效
(function($) {
$.tableUI = {
set:function () {
var thisTable = $("table");
$(thisTable).find('tr').hover(function() {
$(this).css({
color: "#ff0011",
background:"blue"
});
}, function () {
$(this).css({
color: '#000000',
background: "white"
});
});
}
}
//直接调用,适合全局的生效的代码
$(function() {
$.tableUI.set();
});
})(jQuery);
*/
//第四种
$(function() {
jQuery.setTableUI = function(table) {
var thisTable = $('#' + table);
$(thisTable).find('tr').hover(function() {
$(this).css({
color:"#ff0011",
background:"tomato",
});
},function () {
$(this).css({
color:"#000000",
background:"white"
});
});
}
console.log(jQuery);
$.setTableUI('table');
});
</script>
</head>
<body>
<table id="table" cellpadding="0" align="center">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>13</td>
<td>14</td>
<td>15</td>
</tr>
</table>
</body>
</html>