如何从一个表单中的多个表中获取每个数据

How to get each data from multiple tables in a form

我在同一个页面中有多个 html table,我想在点击国家时获取国家代码以获得最近的国家代码值

例如:- 1).country-click nearest -- India 例如:- 2).country-click nearest -- 中国 例如:- 3).country-click nearest -- Japan

这是我的table

<table>
  <tr>
    <td><button id="country">Country</button></td>
  </tr>
  <tr>
    <td id="code">India</td>
  </tr>
</table>
<table>
  <tr>
    <td><button id="country">Country</button></td>
  </tr>
  <tr>
    <td id="code">China</td>
  </tr>

</table>
<table>
  <tr>
    <td><button id="country">Country</button></td>
  </tr>
  <tr>
    <td id="code">Japan</td>
  </tr>
</table>

这是脚本代码

$(document).ready(function(){
    $("button").click(function(){
        console.log($(this).parents().closest('tr').find('#code').html());
    });
});

感谢您的建议。

您可以将兄弟姐妹用于 table 行

抱歉代码片段格式化,由于某些原因我无法在此编辑器中格式化它。

您在寻找最近的 tr 方面做得很好,现在您必须检查包含带有“#code”id 的元素的兄弟行(您应该在这里使用 class 而不是 id,id 必须是唯一的,因为berko 评论了)。

这是jquery代码:

$(document).ready(function(){
    $("button").click(function(){             
        alert($(this).closest('tr').siblings().find('#code').html());
    });
});

..这里是片段:

$(document).ready(function(){
      $("button").click(function(){             alert($(this).closest('tr').siblings().find('#code').html());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="country">
  <tr>
    <td><button>Country</button></td>
  </tr>
  <tr>
    <td id="code">India</td>
  </tr>
</table>
<table id='country'>
  <tr>
    <td><button>Country</button></td>
  </tr>
  <tr>
    <td id="code">China</td>
  </tr>

</table>
<table  id="country">
  <tr>
    <td><button>Country</button></td>
  </tr>
  <tr>
    <td id="code">Japan</td>
  </tr>
</table>