我怎样才能得到最后一个的价值?

时间:2017-10-10 10:43:27

标签: javascript jquery cookies

我需要点击所有复选框打印Emails的字样。我怎样才能做到这一点?这是我的HTML结构:

$('td input').on('change', function() {
  var header_name = $(this).closests('tr').sibilings('th').last().text();
  console.log(header_name);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th><input type="checkbox" class="all_checkboxes"></th>
      <th>Emails</th>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="email"></td>
      <td>email</td>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="gmail"></td>
      <td>gmail</td>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="aol"></td>
      <td>aol</td>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="chmail"></td>
      <td>chmail</td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:6)

首先你有一些错别字。 closests()应为closest()sibilings()必须为siblings()

问题本身是因为您的DOM遍历不正确。您正试图查看已点击th的父tr的同级input,当您所瞄准的th处于完全不同的行时。< / p>

要解决此问题,您应该使用closest()获取table,然后find() tr:last,如下所示:

$('td input').on('change', function() {
  var header_name = $(this).closest('table').find('th:last').text();
  console.log(header_name);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <th><input type="checkbox" class="all_checkboxes"></th>
      <th>Emails</th>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="email"></td>
      <td>email</td>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="gmail"></td>
      <td>gmail</td>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="aol"></td>
      <td>aol</td>
    </tr>
    <tr>
      <td><input type="checkbox" data-id="chmail"></td>
      <td>chmail</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
       <tr>
          <th><input type="checkbox" class="all_checkboxes"></th>
          <th>Emails</th>
       </tr>
       <tr>
          <td><input type="checkbox" data-id="email"></td>
          <td>email</td>
       </tr>
       <tr>
          <td><input type="checkbox" data-id="gmail"></td>
          <td>gmail</td>
       </tr>
       <tr>
          <td><input type="checkbox" data-id="aol"></td>
          <td>aol</td>
       </tr>
       <tr>
          <td><input type="checkbox" data-id="chmail"></td>
          <td>chmail</td>
       </tr>
    </tbody>    
</table>
<script>
    $('td input, th input').on('change', function(){
        var header_name = $( "tr:first" ).last().text();
        console.log(header_name);
    })
</script>