Jquery .Toggle()基于colgroup col id

时间:2012-06-11 19:36:29

标签: javascript jquery html-table toggle colgroup

小提琴是here

我无法通过colgroup的col id抓取实际列来切换它。我的索引正确匹配,但我不明白如何使用colgroup的功能来抓取整个列。这是我目前的尝试(一直在小提琴的底部):

    //Column Button Hider
    $('fieldset.techtable input.column[type=checkbox]').on('change', function() {
        var index = $(this).prevAll('input.column').length+2;
        console.log(index);
        $('fieldset.techtable' #col'+index').toggle()
            //($('#col'+index).toggle());
    });

,这是表和colgroup:

<section class="techtable">
        <h1>Technologies / Compliance / Certifications</h1>
        <table cellspacing="0">
            <colgroup>
                <col id="col0">
                <col id="col1">
                <col id="col2">
                <col id="col3">
                <col id="col4">
                <col id="col5">
                <col id="col6">
            </colgroup>
            <thead>
                <tr>
                    <th>Category</th>
                    <th>Skill</th>
                    <th>Version(s)</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                    <th>Elapsed Time</th>
                    <th>Expertise Rating</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Technology</td>
                    <td>J2EE</td>
                    <td>1.5, 1.6, 1.7</td>
                    <td>November, 2011</td>
                    <td></td>
                    <td></td>
                    <td>2</td>
                </tr>
                </tr>...repeating...</tr>
            </tbody>
        </table>
    </section>

我想尝试利用colgroup的强大功能,但我不确定是否应该使用类ID(如果是,在哪里?在col组ID,<th>?或每个<td> ?)。

<th>是否会干扰<colgroup>?也许措辞更好,我应该引用th而不是尝试使用colgroup吗?

语法正确方向上的一点是有帮助的,并且总是赞赏一行代码来帮助,但对于这一点,我试图避免将其扩展为更多代码行,除非我忽略了方法论。我假设我不只是正确地抓住col id,但你的反馈可能证明我错了。

4 个答案:

答案 0 :(得分:2)

如果您试图隐藏特定的数据列,则将col隐藏在colgroup中将无法执行此操作。

var colIndex = 0; // first column
$(myTable).find("td,th").filter(":nth-child(" + (colIndex+1) + ")").toggle();

我修改了此代码以使用您的表格。这是更新后的fiddle

 var index = $(this).prevAll('input.column').length+2;
 $('colgroup').parent('table').find("td,th").filter(":nth-child(" + (index+1) + ")").toggle();  

答案 1 :(得分:1)

你想这样做吗?

$('fieldset.techtable #col' + index).toggle();

由于id在页面中是唯一的,因此通常只需定位:

$('#col' + index).toggle();

答案 2 :(得分:1)

尝试以下方法:

$(“。techtable td:nth-​​child(”+ index + 1 +“)”)。toggle();

Hide/Show Column in an HTML Table

上看到了这一点

答案 3 :(得分:0)

我认为您无法切换列的可见性,因为列的元数据/伪元素多于页面上的实际元素(实际上是每个{{1}的第N tr个你试图切换)。我知道在出于这个原因尝试一致地设置它们时会出现问题(请参阅my answer here进行解释/调查)。

相关问题