Traversing through a html table

Traversing through a html table

本文关键字:table html through Traversing      更新时间:2023-09-26

我有一个具有以下结构的表:

<table>
  <tr>
    <td><a href = "#">link1</a></td>
    <td><a href = "#">link2</a></td>
    <td><a href = "#">link3</a></td>
    <td><input type = "checkbox" onclick = "func()"></td>
  </tr>
</table>
function func(){
  //I have to alert link1 here. 
}

谁能告诉我怎么做?

提前谢谢。

编辑1:有相同类型的多行,单击特定复选框应提醒相应的<a>文本。

你可以用jquery这样做。只需更改eq的数量即可。所有带有input的表都将运行class checkbox。你可以玩它。

$('.checkbox').on('click',function(){
  var e = $(this).closest('table').find('td a');
  alert(e.eq(0).text());
});
table{
  border: 1px solid red;
  margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table1">
  <tr>
    <td><a href = "#">link1</a></td>
    <td><a href = "#">link2</a></td>
    <td><a href = "#">link3</a></td>
    <td><input type = "checkbox" class="checkbox"></td>
  </tr>
</table>
<table class="table2">
  <tr>
    <td><a href = "#">link4</a></td>
    <td><a href = "#">link5</a></td>
    <td><a href = "#">link6</a></td>
    <td><input type = "checkbox" class="checkbox"></td>
  </tr>
</table>

由于您使用的是 jQuery,请使用 jQuery 处理程序,您可以在其中找到同一行中的a

jQuery(function($) {
  $('#my-table input[type="checkbox"]').change(function() {
    alert($(this).closest('tr').find('td:first-child a').text())
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my-table">
  <tr>
    <td><a href="#">link-1-1</a></td>
    <td><a href="#">link-1-2</a></td>
    <td><a href="#">link-1-3</a></td>
    <td>
      <input type="checkbox">
    </td>
  </tr>
  <tr>
    <td><a href="#">link-2-1</a></td>
    <td><a href="#">link-2-2</a></td>
    <td><a href="#">link-2-3</a></td>
    <td>
      <input type="checkbox">
    </td>
  </tr>
</table>