如何找到附加了特定类的tr并获取每个td的详细信息 - jquery

时间:2017-05-05 08:12:23

标签: javascript jquery html css

请查看这个小提琴 https://jsfiddle.net/shaswatatripathy/y7jqb5hp/7/

function getdetails(row) {
  $("#tableID tbody tr").each(function() {
    $(this).removeClass("highlightRowSelected");
  });
  $(row).addClass("highlightRowSelected");
}

function DetailsOfTheSelectedRows() {
  $.each($("#tableID tbody tr.highlightRowSelected"), function() {
    $('#txtBoxValue').value = $(this).find('td:eq(1)').text();
  });
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

.highlightRowSelected {
  background-color: #e2e2e2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableID">
  <tr onclick="getdetails(this)">
    <th>checkbox</th>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr onclick="getdetails(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Alfreds </td>
    <td>Maria </td>
    <td>Germany</td>
  </tr>
  <tr onclick="getdetails(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Centro </td>
    <td>Francisco </td>
    <td>Mexico</td>
  </tr>
  <tr onclick="getdetails(this)">
    <td><input name="eachRow" type="checkbox" /> </td>
    <td>Ernst </td>
    <td>Roland </td>
    <td>Austria</td>
</table>

<input type="button" onclick="DetailsOfTheSelectedRows()" value="Selected Row" />

<input type="text" id="txtBoxValue" />

在实际项目中,整个tbody是动态的,所以不要更改Html和getdetails(row)函数

表行可以动态添加多个类。

我的工作是只获取附加了highlightRowSelected的那一行,获取第一列值并在文本框中显示

Jquery函数DetailsOfTheSelectedRows也必须是动态的,因此选择器应该在那里,并且只有一行将附加该类名。

所以如何写DetailsOfTheSelectedRows

2 个答案:

答案 0 :(得分:1)

我将您的代码更改为

function DetailsOfTheSelectedRows()
{
 $.each($(".highlightRowSelected",'#tableID'), function () {

       $('#txtBoxValue').val($(this).find('td:eq(1)').text());

    });

}

更新了小提琴 https://jsfiddle.net/y7jqb5hp/9/

检查

答案 1 :(得分:1)

DetailsOfTheSelectedRows()函数中的单行...

function DetailsOfTheSelectedRows() {
  $('#txtBoxValue').val($('#tableID tr.highlightRowSelected td:eq(1)').text())
}

这是你的小提琴,更新时间:https://jsfiddle.net/9cuoe5df/