如何通过jQuery获取选定行的列值,单击元素调用方法来检索值

how to get values of columns for a selected row through jQuery on click of element calling method to retrieve value

本文关键字:单击 元素 方法 检索 调用 获取 jQuery 何通过      更新时间:2023-09-26

在这里,我试图通过jquery获取选定行的特定列的值。在下面的代码中,我有两行没有任何id。我尝试了以下方式,并获得该列的两行值相互附加。如何仅使用jquery获取该行的值。我想在点击该元素时调用测试函数,不想使用http://jsfiddle.net/SSS83/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
function test(){
var id = $(".use-address").closest("tr").find('td:eq(2)').text();
  alert(id);
}
    </script>
</head>
<body>
<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>Glas</td>
      <td>G0 0XX</td>
      <td>United Kingdom</td>
      <td>
        <button type="button" class="use-address" onclick="test();">Use</button>
      </td>
    </tr>
    <tr>
      <td class="nr"><span>30</span>
      </td>
      <td>Some Street 2</td>
      <td>Glasgow</td>
      <td>G0 0XX</td>
      <td>United Kingdom</td>
      <td>
          <button type="button" class="use-address" onclick="test();">Use</button>
      </td>
    </tr>
  </tbody>
</table>
</body>
</html>

不知道为什么你不想使用jQuery点击事件!!

无论如何,如果你想坚持你的测试函数,你需要告诉函数从哪里被调用。

所以改变

<button type="button" class="use-address" onclick="test();">Use</button>

<button type="button" class="use-address" onclick="test(this);">Use</button>

并将test函数更新为

function test(el) {
    var id = $(el).closest("tr").find('td:eq(2)').text();
    alert(id);
}

享受! !


如果您改变了主意,可以使用以下代码

jQuery('document').ready(function() {
        jQuery('.use-address').on('click',function() {
            var id = $(this).closest("tr").find('td:eq(2)').text();
            alert(id);
      })
 });

基于TD的点击:

$('td').on('click',function() {
      //get the column of the TD
      var myCol = $(this).index();
      //loop through the rows of this table, get the TD in the same column
      $(this).parent('table').find('tr').each(function() {
         var colValue = $(this).find('td').eq(myIndex).html()
      }
})

循环中的"colValue"将获取该位置的TD的内容。