在某个单元格之后引用所有表格单元格

时间:2013-07-08 23:21:25

标签: jquery html

我如何改变跟随某个细胞的表格中的细胞?我无法将其与.parent().nextAll().index()

一起使用

我很抱歉,但我没有任何代码可以发布。我认为这是一个普遍的问题。

3 个答案:

答案 0 :(得分:1)

单元格实际上并不是HTML中的顺序,因此您不能只使用同一级别的所有内容(使用nextAll等)。假设你有这张桌子:

<table>
    <tbody>
        <tr>
            <td>one</td>
            <td id="two">two</td>
            <td>three</td>
        </tr>
        <tr>
            <td>four</td>
            <td>five</td>
            <td>six</td>
        </tr>
    </tbody>
</table>

...并且您希望在“two之后突出显示每个单元格,这将遍历并选择这些单元格:

$('table td:gt(' + $('#two').index() + ')').each(function() {
    console.log($(this).text()); // or whatever you want to do with the cell
});

演示Fiddle here

答案 1 :(得分:0)

可能不是最有效的解决方案,但它完成了工作:

这里的基本策略是:(a)选择当前单元格之后的兄弟节点,(b)跳转到行元素,并在当前行之后的每一行中,抓取TD元素并添加到兄弟列表中。

<!doctype html>
<html>
<head><script src="../lib/jquery-1.9.1.js"></script>
<style>
table { border:1px solid black; }
thead th { border-bottom:1px solid black; }
tfoot th { border-top:1px solid black; }
</style>
<script>
$(function() {

    $('tbody').find('td')
        .click(function(event) {
            var $cell           = $(event.target),
                $siblings       = $cell.nextAll('td'),
                $remainingCells = $cell.closest('tr').nextAll().find('td');

            $siblings.add($remainingCells).each(function(index, element) {
                console.info(index + ':', $(element).text());
            });
        });

});
</script>
</head>
<body>
<table>
    <thead>
        <tr>
            <th>#</th>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Alpha</td>
            <td>Bravo</td>
            <td>Charlie</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Delta</td>
            <td>Echo</td>
            <td>Foxtrot</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Golf</td>
            <td>Hotel</td>
            <td>India</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th>#</th>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
    </tfoot>
</table>

答案 2 :(得分:-1)

// Selecting all <td>s after <td id="i-want">
$('td#i-want ~ td')

// Selecting the next <td> after <td id="i-want">
$('td#i-want + td')