Javascript 如何通过jQuery在单击元素调用方法以检索值时获取所选行的列值

Javascript 如何通过jQuery在单击元素调用方法以检索值时获取所选行的列值,javascript,jquery,Javascript,Jquery,在这里,我试图通过jquery获取所选行的特定列的值。在下面的代码中,我有两行没有任何id。我尝试按照下面的方法获取该列的两行值,并将其相互追加。如何仅使用jquery获取该行的值。我想在单击该元素时调用test函数,不想使用 功能测试(){ var id=$(“.use address”).closest(“tr”).find('td:eq(2)').text(); 警报(id); } 姓名/编号。 大街 镇 邮政编码 国 选择权 50 某条街1 玻璃 G0 0XX 大不列颠联合王国 使用

在这里,我试图通过jquery获取所选行的特定列的值。在下面的代码中,我有两行没有任何id。我尝试按照下面的方法获取该列的两行值,并将其相互追加。如何仅使用jquery获取该行的值。我想在单击该元素时调用test函数,不想使用


功能测试(){
var id=$(“.use address”).closest(“tr”).find('td:eq(2)').text();
警报(id);
}
姓名/编号。
大街
镇
邮政编码
国
选择权
50
某条街1
玻璃
G0 0XX
大不列颠联合王国
使用
30
某条街2
格拉斯哥
G0 0XX
大不列颠联合王国
使用

基于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的内容。

基于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的内容。

不确定为什么不想使用jQuery单击事件

无论如何,如果您想继续使用您的测试函数,您需要告诉函数是从哪里调用的

所以改变现状

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


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

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

不确定为什么不想使用jQuery单击事件

无论如何,如果您想继续使用您的测试函数,您需要告诉函数是从哪里调用的

所以改变现状

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


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

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

是否需要将上述代码添加到测试函数中?否。它使用对TD的实际单击来确定选择了哪一列。是否需要将上述代码添加到测试函数中?否。它使用对TD的实际单击来确定选择了哪一列。