单击按钮获取表格行的内容

时间:2013-01-22 14:05:41

标签: javascript jquery button onclick html-table

我需要提取表格中每列的详细信息。例如,列“Name / Nr。”。

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

问题:我的代码只选择了第<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>

10 个答案:

答案 0 :(得分:213)

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

答案

$(".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>

获取所有表格单元格<td>

所以我们有$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

获取特定的<td>

与前一个类似,但我们可以指定子<td>元素的索引。

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() - 获取匹配元素集中每个元素的前一个兄弟

答案 1 :(得分:8)

试试这个:

$(".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

答案 2 :(得分:8)

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

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

Example fiddle

答案 3 :(得分:1)

选择器".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
    });
});

答案 4 :(得分:1)

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()"

答案 5 :(得分:0)

使用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 );
    });
});

答案 6 :(得分:0)

    var mongoose = require("mongoose");

    var campgroundSchema = new mongoose.Schema({
       name: String,
       image: String,
       description: String,
       comments: [
          {
             type: mongoose.Schema.Types.ObjectId,
             ref: "Comment"
          }
       ]
    });


module.exports = mongoose.model("Campground", campgroundSchema);

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

答案 7 :(得分:0)

这是代表简单示例的完整代码

<!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>

答案 8 :(得分:0)

将以下代码放在header部分

<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>

答案 9 :(得分:0)

试试这个,只选择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>