【问题标题】:JQuery - find first sibling matches selectorJQuery - 查找第一个兄弟匹配选择器
【发布时间】:2014-07-02 20:50:53
【问题描述】:

如何获取列表中与选择器匹配的第一个(下一个)元素?

例子:

<table>
  <tr class="test"><td>not this one</td></tr>
  <tr><td><a title="test">click</a></td></tr>
  <tr><td>not this one</td></tr>
  <tr class="test"><td>this one</td></tr>
  <tr class="test"><td>ignore this as well</td></tr>
</table>

$("a").on('click', function(eve){
  $(this).parents("tr").???(".test").toggle();
});

编辑

我需要下一行。兄弟姐妹也得到其他人(如第一行)

【问题讨论】:

  • 你想做什么??
  • 我有一些动态行由上一个行打开和关闭。我不能使用'next()',因为我不知道我将拥有哪些行 - 以及有多少。

标签: jquery next siblings


【解决方案1】:

使用.nextAll() 获取元素的以下同级元素,使用:first 获取第一个匹配元素。

试试这个:

$("a").on('click', function(eve){
  $(this).parents("tr").nextAll(".test:first").toggle();
});

DEMO

【讨论】:

    【解决方案2】:

    你可以尝试使用 jQuery eq();

    给定一个表示一组 DOM 元素的 jQuery 对象,.eq() 方法从该集合中的一个元素构造一个新的 jQuery 对象。提供的索引标识该元素在集合中的位置。 Documentation on jQuery

    <table>
      <tr class="test"><td>not this one</td></tr>
      <tr><td><a title="test">click</a></td></tr>
      <tr><td>not this one</td></tr>
      <tr class="test"><td>this one</td></tr>
      <tr class="test"><td>ignore this as well</td></tr>
    </table>
    

    代码将选择带有 的类“test”的 2º 同级,它是被点击的 的父级之一(反向红色,你得到了你的代码) :

    $("a").on('click', function(){
      $(this).parents("tr").siblings(".test").eq(1).toggle();
    });
    

    Check the Pen!

    【讨论】:

    • Doesn't 100% answer OP's question as 1) OP 要求下一个 sbilings 因此 nextAll 而不是 siblings (也选择之前的那些) 和 2) 他要求下一个 (第一个)因此eq(0) 而不是eq(1)。尽管您提到它选择了第二个,但直接回答所提问题仍然是更好的做法:)

    【解决方案3】:

    您可以使用.next() 选择器:

    Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

    对于您的情况,请使用

    $(this).parents("tr").next().next()

    $(this).closest("tr").next().next()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-09
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多