jquery,从非直接兄弟姐妹那里获取“最接近”的引用

问题描述 投票:0回答:1

看这个结构:

我需要从我点击的任何地方获得“最接近的”隐藏输入参考

关注:

  • 起点(我点击的地方)和目标不是直接兄弟
  • 我不能使用唯一或复合属性
<tr>
    <th>
        <input type="hidden" />       //hidden 1
    </th>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
</tr>
<tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
</tr>
<tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
</tr>
<tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
</tr>
<tr>
    <th>
        <input type="hidden" />       //hidden 2
    </th>
    <th>
        <i onclick="search(this)">    //get reference to hidden 2 from here
    </th>
</tr>
<tr>
    <th>
        <i onclick="search(this)">     //get reference to hidden 2 from here
    </th>
</tr>
<tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 2 from here
    </th>
</tr>
....
jquery css-selectors jquery-selectors
1个回答
0
投票

您想获得当前行中最接近的

input
及其之前的兄弟姐妹。

function search(el) {
 $(el).closest("tr").add($(el).closest("tr").prevAll("tr")).find("input").last().css("border-color", "red");
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th>
      <input type="text"/> //hidden 1
    </th>
    <th>
      <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
  </tr>
  <tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
  </tr>
  <tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
  </tr>
  <tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 1 from here
    </th>
  </tr>
  <tr>
    <th>
        <input type="text"/>       //hidden 2
    </th>
    <th>
        <i onclick="search(this)">    //get reference to hidden 2 from here
    </th>
  </tr>
  <tr>
    <th>
        <i onclick="search(this)">     //get reference to hidden 2 from here
    </th>
  </tr>
  <tr>
    <th>
        <i onclick="search(this)">    //get reference to hidden 2 from here
    </th>
  </tr>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.