【问题标题】:Find ID of next instance of a specific class查找特定类的下一个实例的 ID
【发布时间】:2022-01-21 03:28:06
【问题描述】:

我正在尝试查找特定类 (findMe) 的下一个实例的 ID(test1、test2、test3 等)。

这是我的代码: HTML:

    <div class="container">
  <table>
    <tr id="test1" class="findMe">
      <td>
      <button class="next">Next</button>
      </td>
    </tr>
    <tr id="test2" class="findMe">
      <td>
      <button class="next">Next</button>
      </td>
    </tr>
  </table>
    <div id="test3" class="findMe">
    </div>
  </container>

JS:

$(".next").click(function() {
console.log($(this).parent().closest(".findMe").next().attr('id'));
})

我可以找到 ID“test2”,但找不到“test3”。为什么?

【问题讨论】:

    标签: javascript html jquery


    【解决方案1】:

    第二个.findMe 与第三个.findMe 最近的祖先是祖父母,而不是父母。 (&lt;tr&gt;&lt;tbody&gt; 内。)

    虽然您可以通过使动态 DOM 导航更灵活来解决它(有点),但我认为更简单的方法是选择所有 .findMes,然后访问下一个索引。

    const findMes = $('.findMe');
    const thisIndex = findMes.index(this);
    console.log(findMes[thisIndex + 1]?.id);
    

    您也可以使用getElementsByClassName,其集合是实时的,而不是每次都重新选择所有元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-24
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 2016-05-23
      相关资源
      最近更新 更多