table表格根據返回數據相同來合併對應的單元格(方法)

$("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
                    }
            });
       });
 });

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章