动态计算并设置colspan值 [英] Calculate and set colspan value dynamically

查看:688
本文介绍了动态计算并设置colspan值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单元格中有一个包含冗余数据的表。 [左表]

I have got a table with redundant data in cells. [Left table]

我需要将它们加入一个单元格。 [右表]

I need to join them into one cell. [Right table]

表格结构:

<table>
  <tr>
    <td class="bold">Value1:</td>
    <td class="green">A</td>
    <td class="green">A</td>
    <td class="green">A</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="green">B</td>
    <td class="green">B</td>
  </tr>
  <tr>
    <td class="bold">Value2:</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="green">C</td>
    <td class="green">C</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="green">D</td>
    <td>&nbsp;</td>
  </tr>
</table>

我能够隐藏冗余单元格,但我需要设置colspan。

I am able to hide redundant cell, but I need to set colspan somehow.

$(document).ready(function () {

var all = $('.green');
var seen = {};
all.each(function () {
    var txt = $(this).text();
    if (seen[txt]) {
        $(this).hide();
    }
    else {
        seen[txt] = true;
    }
});


});

谢谢。

推荐答案

var first;
var prev = undefined;
var colspan = 1;

var setColspan = function () {
    first.attr('colspan', colspan);
    colspan = 1;
}

all.each(function () {
    var txt = $(this).text();
    if (prev === txt) {
        colspan += 1;
        $(this).remove();
    } else {
        // doesnt match, set colspan on first and reset colspan counter
        if (colspan > 1) {
            setColspan();
        }
        first = $(this);
        prev = txt;
    }
});

if (colspan > 1) {
    setColspan();
} 

认为它可以做你想要的,检查匹配列值的连续块,如果它找到一个匹配,它会删除它,当它找不到匹配并且colspan足够大时它会在列表中的第一个上设置colspan然后重置。如果连续值跨越一行的末尾并进入下一行的开头,则它不起作用。如果是这种情况会想要逐行进行

Think it does what you want, checks for consecutive blocks of matching column values, if it finds a match, it removes it, when it doesnt find a match and colspan is large enough it sets the colspan on the first in the list and then resets. it doesnt work if you have consecutive values that span end of one row and into the beginning of the next. would want to do it row by row if that is the case

如果最后一组列也是连续的,则使用边缘情况更新。在那种情况下,它不会设置colspan。

updated above with edge case if last set of columns are consecutive as well. it wouldnt set the colspan in that case then.

这篇关于动态计算并设置colspan值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆