【问题标题】:Traversing hidden cols in html table遍历html表中的隐藏列
【发布时间】:2011-08-02 19:20:16
【问题描述】:

也许这个问题太简单了……我对 html、css、dom 和 javascript 的理解非常好,但是我在尝试让 jQuery 为我工作时遇到了非常艰难的时期。假设我有以下 4 列表格,隐藏了第 1 列和第 3 列:

<table id="mytable">
  <thead>  
    <tr> 
      <th class="hidden">Column1</th> 
      <th>Column2</th>    
      <th class="hidden">Column3</th> 
      <th>Column4</th>
    </tr>
  </thead>
  <tbody> 
    <tr> 
      <td class="hidden">Value1</td> 
      <td>Isle of Palms</td>   
      <td class="hidden">Value3</td>  
      <td>Value4</td> 
    </tr> 
  </tbody>
</table>      

然后我使用下面的代码来隐藏隐藏的类列:

$(function() { 
    $('.hidden').hide();
});             

昨天你们中的一些人告诉我如何使用以下方法获取第一列内容:

$(function() { 
    $(this).find('td.hidden:first').html();
});             

我想要做的是显示一个警报或Thickbox,显示所有隐藏列的标题名称和单元格值:

Column1 = Value1
Column3 = Value3

如果这样做更容易,我可以将所有隐藏列分组在表格的开头(左侧)。

提前致谢。

【问题讨论】:

    标签: jquery html dom traversal html-table


    【解决方案1】:

    试试这个

    var mytable = $('#mytable');
    
    $('#mytable > tbody').delegate('tr', 'click', function (e) {
    
        trToShow = $(this);
    
        var keyValueInfo = mytable.find('th.hidden').map(function () {
    
            // for each th.hidden element, get the corresponding "key = value" string
    
            var i = $(this).index(); // get the index of the th element
    
            // get the td element with the same index as the above th, and get the text inside it
            var value = trToShow.find('td.hidden').filter(function () {
                return $(this).index() === i;
            }).text();
    
            // The above could also be done as (Read documentation of :eq selector)
            // var value = trToShow.find('td:eq(' + i + ')').text();
    
            // get the text inside this th element, which would be our key
            var key = $(this).text();
    
            // return the "key = value" string wrapped up in a div element
            return '<div>' + key + ' = ' + value + '</div>';
    
        }).toArray().join('');
    
    });
    
    // Show a dialog with the above content inside it
    show_dialog_with_stuff(keyValueInfo);
    

    阅读更多index

    我还没有测试过,但如果有的话,应该只是轻微的愚蠢错误。在这里测试http://jsfiddle.net/mb6Gd/

    【讨论】:

    • 我什至可以理解你的代码......所以我不能尝试它。我想在哪里放置带有键+值“值”的警报?感谢您的帮助,并对我的 jquery 无知感到抱歉。
    • 很高兴你问到。这是一种很棒的学习方式 :) 我添加了一些 cmets,让我知道代码现在是否有意义。 编辑:如果您需要更多帮助,请告诉我
    • 好的,我试过了,它返回了隐藏的标题和隐藏的列,但是它返回了表中所有行的值。我只需要显示单击的行。非常感谢。
    • 对不起,不知道你,检查代码的更新版本。我以为只有一个 tr :)
    • Shrikant 当我尝试你的代码时,代码为: $(function() { $('.hidden').hide(); $('#mytable').css({visibility: “可见的”}) });不再起作用了。我需要将它与您的代码集成吗?我根本不懂 jQuery,这对我来说似乎很复杂。
    猜你喜欢
    • 2019-08-29
    • 2016-12-27
    • 2022-11-17
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2011-09-17
    • 2011-08-22
    • 1970-01-01
    相关资源
    最近更新 更多