Javascript 如何获取最后一个th的值?

Javascript 如何获取最后一个th的值?,javascript,jquery,cookies,Javascript,Jquery,Cookies,单击所有复选框后,我需要打印电子邮件的单词。我该怎么做?以下是我的HTML结构: $('td input')。在('change',function()上{ var header_name=$(this).closests('tr').siblings('th').last().text(); console.log(头文件名); }) 电子邮件 电子邮件 gmail 美国在线 奇梅尔 首先,你有几个打字错误closests()应该是closest()而siblings()需要是siblin

单击所有复选框后,我需要打印
电子邮件的单词。我该怎么做?以下是我的HTML结构:

$('td input')。在('change',function()上{
var header_name=$(this).closests('tr').siblings('th').last().text();
console.log(头文件名);
})

电子邮件
电子邮件
gmail
美国在线
奇梅尔

首先,你有几个打字错误
closests()
应该是
closest()
siblings()
需要是
siblings()

问题本身是因为DOM遍历不正确。您正试图查看单击的
输入的父
tr
的兄弟
th
,而您要瞄准的
th
位于完全不同的行中

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

$('td input')。在('change',function()上{
var header_name=$(this).closest('table').find('th:last').text();
console.log(头文件名);
})

电子邮件
电子邮件
gmail
美国在线
奇梅尔

电子邮件
电子邮件
gmail
美国在线
奇梅尔
$('td input,th input')。在('change',function()上{
var header_name=$(“tr:first”).last().text();
console.log(头文件名);
})
A
元素不是
元素的兄弟/姐妹
<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>