【问题标题】:Get info on a particular Table "td" element获取有关特定表“td”元素的信息
【发布时间】:2012-11-02 16:23:34
【问题描述】:

我有一张 10 X 8 的桌子。

每一行有 8 列,即 8 个 td 元素。行中的每个 td 都有一个不同的类。当我单击该行中的任何其他 td 时,是否可以获得该行中第一个 td 元素的信息。

基本上我在每行的第 2 列到第 8 列上创建一个 jquery onclick 事件。当我单击此列中的任何一个(td)时,它应该获取信息,即..,列 1 的 id 或 class 或 name 属性。我需要这个在服务器端发送它代码。

-- 谢谢。

【问题讨论】:

    标签: jquery html-table


    【解决方案1】:

    是的。从单击的元素中,您通过closest 向上导航到该行,然后您可以使用findchildren 找到具有相关类的td(如果您有嵌套表,可能是children):

    function clickHandler(e) {
        var cell = $(e.target).closest('tr').children('td.foo');
        // ...
    }
    

    或者如果你总是想要第一个td:

    var cell = $(e.target).closest('tr').children('td').first();
    

    如果将该处理程序分配给表中的任何tdtr,或者实际上分配给整个tbodytable,则该处理程序将起作用。

    Live Example | Source

    JavaScript:

    jQuery(function($) {
    
      // Put the handler on the tbody
      $("#target").click(clickHandler);
    
      function clickHandler(e) {
        var td = $(e.target).closest('tr').children('td').first();
        display("The text of the first <code>td</code> in that row is: " + td.text());
      }
    
      function display(msg) {
        $("<p>").html(String(msg)).appendTo(document.body);
      }
    
    });
    

    HTML:

    <table>
      <tbody id="target">
      <tr>
        <td class="one">This is one in row 0</td>
        <td class="two">This is two in row 0</td>
        <td class="three">This is three in row 0</td>
      </tr>
      <tr>
        <td class="one">This is one in row 1</td>
        <td class="two">This is two in row 1</td>
        <td class="three">This is three in row 1</td>
      </tr>
      <tr>
        <td class="one">This is one in row 2</td>
        <td class="two">This is two in row 2</td>
        <td class="three">This is three in row 2</td>
      </tr>
      </tbody>
    </table>
    

    【讨论】:

    • 感谢您的详细信息,它的工作。顺便说一句,在点击事件中,我可以附加一个隐藏的输入,其中包含 name="第一个 td 的名称:和 value="第一个 td 的值"。我尝试使用 - $("#tv-shows -feeds-form").append('
      @SangramAnand: td elements 既没有name 属性也没有value,这就是为什么这不起作用(cell.attr("name")cell.val() 都可能回来"")。您可以按照您的指示附加一个字段,但我不知道您想要单元格的哪个部分作为名称和值。 (也许“值”是指单元格的文本?那是cell.text()。但我不知道你的名字是什么意思。)无论如何,这将是一个不同的问题。我相信这个问题已经得到解答。 :-)
    • @SangramAnand:很高兴有帮助。 :-)
    【解决方案2】:

    基本上你可以这样:

    $('td.column2-8').click(function()
    {
    var firstTdData = $(this).parent().children('td:first').html();
    });
    

    【讨论】:

      【解决方案3】:
      $('td').click( function(){
          var $elem = $(this).parent('tr').children('td:first');
          var elem_id = $elem.prop('id'); // or $elem.attr('id');
          .... // for class, name, etc.
      });
      

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签