jQuery 选择器来自 Table

jQuery Selector From Table

我有一个 table 如下所示:

<table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button id="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button id="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button id="getVal">Get</button></td>
<tr>
</table>

我想单击 'Get' 按钮然后获取 tr 中的所有 td 值。我尝试了这段代码,但它不起作用。

<script type="text/javascript">
    $(document).ready(function() {
        $('#getVal').click(function () {            
         var name    = $(this).find('td:first');
         var surname = $(this).find('td:second');
        });
    });
</script>

我该怎么做?请帮助我!

您不能多次使用相同的 id。给他们一个 class 代替。

会变成这样:

<table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button class="getVal">Get</button></td>
<tr>
</table>

只要你确定它总是第一个和第二个<td>你就可以使用下面的jQuery(仍然感觉很hacky)。

$('.getVal').click(function () {            
  var name    = $(this).parent().parent().find('td:first').text();
  var surname = $(this).parent().parent().find('td:nth-child(2)').text();
  console.log(name);
  console.log(surname);
});

一个有效的 JSFiddle can be found here

这样做,

<table>
    <tr>
        <td>james</td>
        <td>sawyer</td>
        <td><button class="get_button">Get</button></td>
    <tr>
    <tr>
        <td>kate</td>
        <td>deluna</td>
        <td><button class="get_button">Get</button></td>
    <tr>
    <tr>
        <td>tupac</td>
        <td>shakur</td>
        <td><button class="get_button">Get</button></td>
    <tr>
</table>

然后 select 你的 td 基于 class,如下所示。

<script type="text/javascript">
    $(document).ready(function() {
        $('.get_button').click(function () {            
            var name    = $(this).find('td:first');
            var surname = $(this).find('td:second');
        });
    });
</script>
Please try this one

 $(document).ready(function() {
        $('.getVal').click(function () {  
         var name    = $(this).parents('tr').find('td:nth-child(1)').text();
     var surname = $(this).parents('tr').find('td:nth-child(2)').text();
     
    alert(name);
    alert(surname)
         
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button class="getVal">Get</button></td>
<tr>
</table>