与点击的td相比,如何选择第一个td

时间:2018-10-24 15:13:59

标签: javascript jquery jquery-selectors

如果选择器只是像<tr>这样的$('tr'),但我的目标是td,那应该很容易。例如,单击此处或td 2等。我希望将第一个td的内容与单击的td进行比较。也就是说,在这种情况下,td 1。

//And this is my jQuery code with <tr> .. what about if a select was a <td> ? 
$('tr').on('click', function() {
  var tds = $('td:first-child', this).text();
  alert(tds);
});

//After having documented I found this but that did not help :( 
var td1 = $(this).closest('td.id').prev('').text();
alert(td1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="id"> td 1 </td>
    <td> td 2 </td>
    <td> td 3 </td>
    <td> CLICK HERE </td>
  </tr>
</table>

提前谢谢

2 个答案:

答案 0 :(得分:2)

要获取任何点击的行的第一个td,请使用:first选择器,如下所示:

$('tr').on('click', function() {
  var tds = $(this).find('td:first').text();
});

或者,如果click事件绑定到td本身,请使用closest()获取父项tr,然后找到第一个td

$('td').on('click', function() {
  var tds = $(this).closest('tr').find('td:first').text();
});

答案 1 :(得分:1)

您可以使用jQuery parent()children()函数:

$('td').on('click',function()
  {
     var tr = $(this).parent();
     var tds = tr.children();
     var first_td = tds[0];
     var text = $(first_td).text();
     alert(text);
  });