jQuery 如何通过jQuery获取选定行的列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22636518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:01:08  来源:igfitidea点击:

how to get values of columns for a selected row through jQuery

jquery

提问by b22

here i am trying to fetch values of a particular column for a selected row via jquery.In Following code i have two rows which do not have any id.I tried following way and getting both rows value for that column appending each other.how to get value for that row only using jquery only.

在这里,我试图通过 jquery 获取选定行的特定列的值。在以下代码中,我有两行没有任何 id。我尝试按照以下方式获取该列的两行值,并相互附加。如何仅使用 jquery 获取该行的值。

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

回答by Felix

You need to use $(this)to target current clicked button instead of $(".use-address"):

您需要使用$(this)来定位当前点击的按钮而不是$(".use-address")

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

instead of inline onclickjavascript, you can use .click():

而不是内联onclickjavascript,您可以使用.click()

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

Fiddle Demo

小提琴演示

回答by Sharique

I would recommend to add class to every column (td), so that it will be easier and more future proof, for example in future you split name to first and last name or you added email after name.. etc.

我建议为每一列 (td) 添加类,这样它会更容易,更能证明未来,例如将来你将名字拆分为名字和姓氏,或者在名字之后添加电子邮件......等。

<td class='country'>United Kingdom</td>

$('.use-address').click(function () {
    var id = $(this).closest("tr").find('td.country').text();
    alert(id);
});