jQuery - 选择表列?

时间:2010-12-22 06:54:12

标签: jquery

我正在寻找特定表列中所有单元格的选择器。我想将html添加到单元格内的一些现有文本中。

谢谢!

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

$("#table id").find("TD")

这将为您提供表格中的所有TD。但它也会在任何嵌套表格中为您提供所有TD。

您能提供一些代码来帮助更具体地解决问题吗?

答案 2 :(得分:0)

不需要插件!代码非常简单。

Working jsFiddle example

HTML:

<h1>Add/Remove Column Example:</h1>
<span class="blurb">Instructions:<br/>1. Click Add Column button to append table to end.<br />2. Click <span class="remove">rem</span> to remove THAT column. <br />3. Code is currently set to COLORIZE rather than remove, just adjust in code and click RUN button at top left.</span><br/><br/>
<table class="table-editor" id="table1">
    <colgroup class=""></colgroup>
    <colgroup class=""></colgroup>
    <colgroup class=""></colgroup>
    <colgroup class=""></colgroup>
    <colgroup class=""></colgroup>
    <tbody>
      <tr class="highlighted-row">
        <td>•</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr class="normal-row">
        <td></td>
        <td>•</td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr class="normal-row">
        <td></td>
        <td></td>
        <td>•</td>
        <td></td>
        <td></td>
      </tr>
      <tr class="normal-row">
        <td class='remove'>rem</td>
        <td class='remove'>rem</td>
        <td class='remove'>rem</td>
        <td class='remove'>rem</td>
        <td class='remove'>rem</td>
      </tr>
    </tbody>
</table>
<input id="addcol" type="button" value="Add Column" />

jQuery代码:

$('#addcol').click(function() {
    var $tablerow = $('table.table-editor').find('tr');
    count = 0;

    $tablerow.each(function(index, value){
        count += 1;
        //alert('Working on row: ' + count);
        var $listitem = $(this);
        //alert('ListItem: ' + $listitem.index());
        n = parseInt($listitem.index());
        //alert('Value of n: ' + n);
        if (n == 3) {
            var $newRow = $("<td class='remove'>rem</td>");
            $("table.table-editor tr:eq(" + n + ")").append($newRow);
        }else{
            var $newRow = $("<td>" + n + "</td>");
            $("table.table-editor tr:eq(" + n + ")").append($newRow);
        }
    });
});

$(document).on('click', 'td.remove', function() {
    var ndx = $(this).index() + 1;
    //alert('Val of ndx: ' + ndx);
    $('td:nth-child(' +ndx+ ')').css('background-color','red'); //comment this line to remove (see next line)
    //$('td:nth-child(' +ndx+ ')').remove(); //UNCOMMENT this line to remove (see prev line)
});

参考文献:
Hide table column with single line of jQuery
Use jQuery to delete table row by clicking on it