单击按钮后如何获取第三个先前输入类型时间的 ID

How to get ID of 3rd Previous Input Type Time Once Button is Clicked

我得到了如下输入:

<tr>
    <td>
        <input type='time' id='32'>
    </td>
    <td>
        <input type='text'>
    </td>
</tr>
<tr>
    <td>
        <input type='time'>
    </td>
    <td>
        <input type='time' >
    </td>
    <td>
        <button class='clicker'>Get ID</button>
    </td>
</tr>

当我单击按钮时,我希望 Jquery 或 JS 提醒我上一个输入的第 3 个 ID(其中 type=time),即 32.

我试过以下代码:

alert($(this).prev('input[type=time]').prev('input[type=time]').prev('input[type=time]').attr('id'));

但是,我一直收到 undefined

有什么想法吗?

你可以这样得到idprev() 获取节点中的先前兄弟姐妹,这不是你的情况。

$(this)
  .closest('tr').prev() //get the parent tr, then call prev() to get above tr
  .find('td:first input').attr('id');

你可以像下面那样做。

$('.clicker').click(function() {
    alert($(this)
        .closest('tr')
        .prev('tr')
        .find('input[type=time]').attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td><input type='time' id='32'></td>
        <td><input type='text'></td>
    </tr>
    <tr>
        <td><input type='time'></td>
        <td><input type='time'></td>
        <td><button class='clicker'>Get ID</button></td>
    </tr>
</table>