<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#table1{border-collapse: collapse;}
#table1 td{border: 1px solid #000;width: 50px;text-align: center;}
</style>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script>
console.log($("td").attr("rowSpan"));//所有td的rowSpan属性的默认值都为undefined
jQuery.fn.rowspan = function(colIdx) { //封装的一个JQuery小插件
console.log(this);
return this.each(function(){
console.log(this)
var that;//用来保存含 有重复内容的列中的第一个td
console.log(that);//undefined
var r = 1;
$('tr').each(function() { //外层循环控制行
$('td:eq('+colIdx+')', this).each(function() { //内层循环控制列
//第一次遇到if条件时 this为 #td01 显然 undefined == “333” 结果为 false 进入else语句,把闭包中声明的变量that设置为#td01,从此以后that的值恒为#td01
//第二次遇到if条件时 this为 #td02 显然 $(“#td01”).html() == $(“#td02”).html() 结果为 true 进入if语句,把#td01的rowSpan设置为2,并隐藏#td02
//第三次遇到if条件时 this为 #td03 显然 $(“#td01”).html() == $(“#td03”).html() 结果为 true 进入if语句,把#td01的rowSpan设置为3,并隐藏#td03
// 过程:先执行1次else语句,再执行2次if语句
if ($(that).html() == $(this).html()) {
r++;//遍历#td02,#td03,当遇到1个内容相等的td,rowspan=2;当遇到第2个内容相等的td,rowspan=3;......
$(that).attr("rowSpan",r);//r自增1 然后赋值给#td01的rowSpan属性
console.log(that);//#td01
$(this).hide(); //分别隐藏#td02,#td03
console.log(this);// #td02,#td03
} else {
that = this;//#td01(#td02,#td03进不来)
}
});
});
});
}
//调用jq里面自定义的方法rowspan(colIdx)
$(document).on("DOMContentLoaded",function () {
$("#table1").rowspan(0);//传入的参数是对应的列数从0开始 第一列合并相同
// $("#table1").rowspan(2);//传入的参数是对应的列数从0开始 第三列合并相同
})
</script>
</head>
<body>
<table id="table1">
<tr id="tr01">
<td>111</td>
<td>222</td>
<td id="td01">333</td>
<td></td>
</tr>
<tr>
<td>111</td>
<td>555</td>
<td id="td02">333</td>
<td></td>
</tr>
<tr>
<td>111</td>
<td>888</td>
<td id="td03">333</td>
<td></td>
</tr>
</table>
</html>
注解:
1、jQuery.fn是jQuery.prototype的简写,jq底层jQuery.fn = jQuery.prototype,即向jQuery对象的原型里面添加方法。通过jQuery()或者$()新建的jq对象会自动继承jQuery.prototype里面的方法;
2、新添加的方法名为 rowspan(colIdx);一劳永逸! 添加一次,后面可以直接调用rowspan()方法,如$("#table1").rowspan(0);
3、整体结构f1>f2>f3>f4,4层函数嵌套,形成3个闭包,即闭包f2,f3,f4
闭包f2内部保存的私有变量:colIdx
闭包f3内部保存的私有变量:that 和 r
闭包f4内部保存的私有变量:this (这里的this指向当前td的执行环境context,即当前td所在的tr,而f4内部的this指向#td01,#td02,#td03,即重复列当中的每一个td)
4、this的指向:
函数f1内部的this指向:即将调用rowspan()方法的对象,如$("#table1").rowspan(0);this指向$("#table1")对象
函数f2内部的this指向:undified
函数f3内部的this指向:tr
函数f4内部的this指向:#td01,#td02,#td03,即重复列当中的每一个td
每句代码的注释见上面的代码。
效果图: