簡體   English   中英

我怎樣才能得到最后一個的價值?

[英]How can I get the value of the last th?

我需要點擊所有復選框打印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> 

首先你有一些錯別字。 closests()應該是closest()sibilings()必須是siblings()

問題本身是因為您的DOM遍歷不正確。 你想看看同級thtr的點擊input ,當th你的目標是為一個完全不同的行。

要解決這個問題,你應該使用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> 

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM