【问题标题】:Get the contents of a table row with a button click通过单击按钮获取表格行的内容
【发布时间】:2013-01-05 19:02:35
【问题描述】:

我需要提取表中每一列的详细信息。例如,列“姓名/编号”。

  • 该表包含多个地址
  • 每行的最后一列都有一个按钮,可让用户选择列出的地址。

问题:我的代码只选择了第一个<td>,它有一个类nr。我如何让它发挥作用?

这里是 jQuery 位:

$(".use-address").click(function() {
    var id = $("#choose-address-table").find(".nr:first").text();
    $("#resultas").append(id); // Testing: append the contents of the td to a div
});

表格:

<table id="choose-address-table" class="ui-widget ui-widget-content">
    <thead>
        <tr class="ui-widget-header ">
            <th>Name/Nr.</th>
            <th>Street</th>
            <th>Town</th>
            <th>Postcode</th>
            <th>Country</th>
            <th>Options</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="nr"><span>50</span>
            </td>
            <td>Some Street 1</td>
            <td>Leeds</td>
            <td>L0 0XX</td>
            <td>United Kingdom</td>
            <td>
                <button type="button" class="use-address" />
            </td>
        </tr>
        <tr>
            <td class="nr">49</td>
            <td>Some Street 2</td>
            <td>Lancaster</td>
            <td>L0 0XX</td>
            <td>United Kingdom</td>
            <td>
                <button type="button" class="use-address" />
            </td>
        </tr>
    </tbody>
</table>

【问题讨论】:

    标签: javascript jquery button onclick html-table


    【解决方案1】:

    练习的目的是找到包含信息的行。当我们到达那里时,我们可以轻松提取所需的信息。

    回答

    $(".use-address").click(function() {
        var $item = $(this).closest("tr")   // Finds the closest row <tr> 
                           .find(".nr")     // Gets a descendent with class="nr"
                           .text();         // Retrieves the text within <td>
    
        $("#resultas").append($item);       // Outputs the answer
    });
    

    VIEW DEMO

    现在让我们关注在这种情况下的一些常见问题。

    如何找到最近的行?

    使用.closest()

    var $row = $(this).closest("tr");
    

    使用.parent()

    您还可以使用.parent() 方法向上移动DOM 树。这只是有时与.prev().next() 一起使用的替代方案。

    var $row = $(this).parent()             // Moves up from <button> to <td>
                      .parent();            // Moves up from <td> to <tr>
    

    获取所有表格单元格&lt;td&gt;

    所以我们有我们的$row,我们想输出表格单元格文本:

    var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
        $tds = $row.find("td");             // Finds all children <td> elements
    
    $.each($tds, function() {               // Visits every single <td> element
        console.log($(this).text());        // Prints out the text within the <td>
    });
    

    VIEW DEMO

    获取特定的&lt;td&gt;

    与上一个类似,但是我们可以指定子&lt;td&gt; 元素的索引。

    var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
        $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
    
    $.each($tds, function() {                // Visits every single <td> element
        console.log($(this).text());         // Prints out the text within the <td>
    });
    

    VIEW DEMO

    有用的方法

    • .closest() - 获取第一个匹配选择器的元素
    • .parent() - 获取当前匹配元素集中每个元素的父元素
    • .parents() - 获取当前匹配元素集中每个元素的祖先
    • .children() - 获取匹配元素集中每个元素的子元素
    • .siblings() - 获取匹配元素集中每个元素的兄弟姐妹
    • .find() - 获取当前匹配元素集中每个元素的后代
    • .next() - 获取匹配元素集中每个元素的紧随其后的兄弟
    • .prev() - 获取匹配元素集中每个元素的前一个兄弟元素

    【讨论】:

    • 如果我有一个弹出窗口并且我想从页面访问一个表并删除该行怎么办?我尝试了一种方法,但它对我不起作用:/
    • 你能准备一个jsFiddle吗?
    • 这里我在处理动态 ID 值时遇到了类似的问题。请看stackoverflow.com/questions/25772554/…
    • 不知道这个答案如何没有得到更多的支持。很好的提示!只是想添加你总是可以在获取特定行 $(this).closest("tr").find("td:eq(2)").html();您将获得第 2 列。干杯!
    • 我仍然不时使用这个答案。真的很有帮助,做了一些小的修改,基本上适用于每张桌子!
    【解决方案2】:

    您需要更改代码以找到与单击的按钮相关的行。试试这个:

    $(".use-address").click(function() {
        var id = $(this).closest("tr").find(".nr").text();
        $("#resultas").append(id);
    });
    

    Example fiddle

    【讨论】:

      【解决方案3】:

      试试这个:

      $(".use-address").click(function() {
         $(this).closest('tr').find('td').each(function() {
              var textval = $(this).text(); // this will be the text of each <td>
         });
      });
      

      这将找到当前单击按钮的最近的tr(向上通过 DOM),然后循环每个td - 您可能想要创建一个带有值的字符串/数组。

      Example here

      Getting the full address using an array example here

      【讨论】:

        【解决方案4】:
        function useAdress () { 
        var id = $("#choose-address-table").find(".nr:first").text();
        alert (id);
        $("#resultas").append(id); // Testing: append the contents of the td to a div
        };
        

        然后在你的按钮上:

        onclick="useAdress()"
        

        【讨论】:

        • 这和问题中的代码有同样的问题——它总是从表的第一行获取id,不管点击的是哪一行的按钮。
        【解决方案5】:

        选择器".nr:first" 专门寻找所选表格元素中的第一个,也是唯一一个具有"nr" 类的元素。如果您改为调用.find(".nr"),您将获得表中具有"nr" 类的所有元素。一旦你拥有了所有这些元素,你就可以使用.each 方法来迭代它们。例如:

        $(".use-address").click(function() {
            $("#choose-address-table").find(".nr").each(function(i, nrElt) {
                var id = nrElt.text();
                $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
            });
        });
        

        但是,这会让您获得所有表中的 td.nr 元素,而不仅仅是被点击的行中的元素。要进一步将您的选择限制为包含单击按钮的行,请使用.closest 方法,如下所示:

        $(".use-address").click(function() {
            $(this).closest("tr").find(".nr").each(function(i, nrElt) {
                var id = nrElt.text();
                $("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
            });
        });
        

        【讨论】:

          【解决方案6】:

          使用 jquery 在行中查找具有 id 的元素

          $(document).ready(function () {
          $("button").click(function() {
              //find content of different elements inside a row.
              var nameTxt = $(this).closest('tr').find('.name').text();
              var emailTxt = $(this).closest('tr').find('.email').text();
              //assign above variables text1,text2 values to other elements.
              $("#name").val( nameTxt );
              $("#email").val( emailTxt );
              });
          });
          

          【讨论】:

            【解决方案7】:
            var values = [];
            var count = 0;
            $("#tblName").on("click", "tbody tr", function (event) {
               $(this).find("td").each(function () {
                   values[count] = $(this).text();
                   count++;
                });
            });
            

            现在 values 数组包含该行的所有单元格值 可以像 values[0] 点击行的第一个单元格值一样使用

            【讨论】:

              【解决方案8】:

              这是委托的简单示例的完整代码

              <!DOCTYPE html>
              <html lang="en">
              <head>
                <title>Bootstrap Example</title>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
              
              </head>
              <body>
              
              <div class="container">
                <h2>Striped Rows</h2>
                <p>The .table-striped class adds zebra-stripes to a table:</p>            
                <table class="table table-striped">
                  <thead>
                    <tr>
                      <th>Firstname</th>
                      <th>Lastname</th>
                      <th>Email</th>
              
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td>John</td>
                      <td>Doe</td>
                      <td>john@example.com</td>
                      <td>click</td>
                    </tr>
                    <tr>
                      <td>Mary</td>
                      <td>Moe</td>
                      <td>mary@example.com</td>
                      <td>click</td>
                    </tr>
                    <tr>
                      <td>July</td>
                      <td>Dooley</td>
                      <td>july@example.com</td>
                      <td>click</td>
                    </tr>
              
                  </tbody>
                </table>
                <script>
                $(document).ready(function(){
                $("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
                var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
                  $tds = $row.find("td:nth-child(2)");
                   $.each($tds, function() {
                      console.log($(this).text());
                      var x = $(this).text();
                      alert(x);
                  });
                  });
              });
                </script>
              </div>
              
              </body>
              </html>
              

              【讨论】:

                【解决方案9】:

                将以下代码放在标题部分

                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
                

                body中的表格定义为

                <table class="table table-hover">
                            <tr>
                                <th>Name/Nr.</th>
                                <th>Street</th>
                                <th>Town</th>
                                <th>Postcode</th>
                                <th>Country</th>
                                <th>View</th>
                            </tr>
                            
                            <tr>
                                 <td class="nr"><span>50</span></td>
                                 <td>Some Street 1</td>
                                 <td>Leeds</td>
                                 <td>L0 0XX</td>
                                 <td>United Kingdom</td>
                                 <td><button type="button" class="btn grabId" >View</button></td>
                            </tr>
                            
                </table>
                

                然后使用这个脚本

                <script>
                    $(".grabId").click(function() {
                        var $row = $(this).closest("tr");    // Find the row
                        var $siteId = $row.find(".siteId").text(); // Find the text
                        alert($siteId);
                    });
                </script>
                

                【讨论】:

                  【解决方案10】:

                  试试这个,只需选择 javascript 或 jquery 如果没有标题栏,不要减1

                  function rowClicked(element){
                      var rowJavascript = element.parentNode.parentNode;
                      var rowjQuery = $(element).closest("tr");
                      
                      var rowIndexJavascript = rowJavascript.rowIndex-1;
                      var rowIndexjQuery = rowjQuery[0].rowIndex-1;
                      
                      console.log("rowIndexJavascript : ",rowIndexJavascript);
                      console.log("rowIndexjQuery : ",rowIndexjQuery);
                  }
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                  <table>
                  <tr>
                  <th>Row ID</th>
                  <th>Button</th>
                  </tr>
                  <tr>
                  <td>0</td><td><button type="button"  onclick="rowClicked(this)">test1</button></td>
                  </tr>
                  <tr>
                  <td>1</td><td><button type="button" onclick="rowClicked(this)">test2</button></td>
                  </tr>
                  <tr>
                  <td>2</td><td><button type="button" onclick="rowClicked(this)">test3</button></td>
                  </tr>
                  </table>

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2020-11-29
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-05-01
                    • 1970-01-01
                    • 2015-07-10
                    • 1970-01-01
                    相关资源
                    最近更新 更多