$("table tbody").rowspan(colIdx); //通过返回数据的单位名字是否相同,把需要合并的列表合并
jQuery.fn.rowspan = function(colIdx) { //封装的一个JQuery小插件
debugger;
return this.each(function(){
var that;
$('tr', this).each(function(row) {
$('td:nth-child('+colIdx+')', this).filter(':visible').each(function(col) {
if (that!=null && $(this).html() == $(that).html()) {
rowspan = $(that).parent().children().eq(10).attr("rowspan");
if (rowspan == undefined) {
$(that).attr("rowSpan",1);
rowspan = $(that).attr("rowspan"); }
rowspan = Number(rowspan)+1;
$(that).parent().children().eq(10).attr("rowspan",rowspan);
$(this).parent().children().eq(10).hide();
} else {
that = this;
}
});
});
});
}
注:思路详细介绍:
jQuery.fn.rowspan = function(colIdx) { //封装方法
return this.each(function(){
var that;
$(‘tr’, this).each(function(row) { //遍历表格的每一行(tr)标签
$(‘td:nth-child(’+index+’)’, this).filter(’:visible’).each(function(col) {
//过滤不为空的元素标签,并对指定的标签遍历 ; this:指遍历的每一条数据(在这 遍历tr中 索引为index的td标签) ;因为本文需要的效果是根据表格的单位名称是否相同去合并对应的单元格,这里的索引(index)就是调用函数传入的数字;$(‘td:nth-child(3)’)就是找到的就是所有的单位内容的标签)
补充:filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素;
(’:visible’) :可见选择器
官网笔记补充:因为:visible是jQuery扩展而不是CSS规范的一部分,所以使用的查询:visible无法利用本机DOM querySelectorAll()方法提供的性能提升。为了在:visible选择元素时获得最佳性能,请先使用纯CSS选择器选择元素,然后使用.filter(":visible")。
if (that!=null && $(this).html() == $(that).html()) { 重点:条件判断:
思路:判断数据相同,首先想到就是去进行比较,如果数据A == 数据B 相同;就去合并数据A+数据B (数据相邻比较);比较前提:两组进行,自己没法给自己比较,所有我们先声明 var that ;that里面也要存放和this一样的数据内容 两者才能比较 ;所以 当if条件不成立时;that = this;把this赋给that ;再拿this的内容与that内容比较
rowspan = $(that).parent().children().eq(10).attr("rowspan"); //给需要合并的标签加上rowspan属性(本文例子是给相邻td索引为10的td标签合并)
if (rowspan == undefined) { 判断有没有rowspan属性;有 属性值 =1 ;没有则添加属性
$(that).attr("rowspan",1);
rowspan = $(that).attr("rowspan");
}
rowspan = Number(rowspan)+1; 根据相同数据的个数,rowspan的值+=1
$(that).parent().children().eq(10).attr("rowspan",rowspan); 添加属性
$(this).parent().children().eq(10).hide();
}
else {
that = this; //把this 赋给 that
}
});
});
});
}