简体   繁体   English

这是我应该如何在jQuery中使用.next([selector])?

[英]Is this how I should use the .next( [selector] ) in jQuery?

Using jQuery, I have selected an <a> inside a div and want to use $(this) to select the next div (I guess this makes it an uncle?). 使用jQuery,我在div中选择了一个<a>并想使用$(this)来选择下一个div(我想这会让它成为叔叔?)。

I want to use the same class name for all my content so I want to use only relative to $(this) . 我想为我的所有内容使用相同的类名,所以我只想使用相对于$(this)

Here's an example of the behavior I am after: 这是我所追求的行为的一个例子:

<div><a>click</a></div>
<div> SELECT THIS DIV after click a </div>  (real code below)

I have been playing around and it works fine if I don't close the div around the <a> . 我一直在玩,如果我不关闭<a>附近的div,它工作正常。 .next('div") finds the div after the </a> , but I need to close the div of the <a> . (So I guess this makes the <a> a child of the div I am in.) .next('div")</a>之后找到div,但是我需要关闭<a>的div。(所以我想这会使<a>成为我所在的div的一个孩子。)

So I need to access the uncle div of the one I'm in? 所以我需要访问我所在的叔叔div? How would I do that - 我该怎么做 -

Here's what I have been playing with so far: 这是我到目前为止一直在玩的东西:

js: JS:

 $(document).ready(function() {
  $('.demo > .row').hide();  
  $('.demo > .box > a').click(function() {
    $(this).next().slideToggle('fast')
    .siblings('div:visible').slideUp('fast');
  });
});

html: HTML:

<div class="demo">
    <div class="box"><a>Title 1</a></div>
    <div class="row">
        <ul >
            <li> <a >  <img >  </a></li>
        </ul>
    </div>
</div>

Have a look at the traversal functions provided by jQuery. 看看jQuery提供的遍历函数 In this case, you need parent followed by next : 在这种情况下,您需要parent然后是next

$(this).parent().next().slideToggle...

You need to traverse the document tree upwards from the "current" <a> to its parent <div> , and then sideways to find the next <div> : 您需要将文档树从“当前” <a>向上遍历到其父<div> ,然后横向遍历以查找下一个<div>

$(this).closest("div").next().slideToggle('fast')
       .siblings('div:visible').slideUp('fast');

Traversing upwards can be done with a number of functions; 中横过向上可以用许多功能来完成; I prefer closest because it's less susceptive to breaking if your markup changes. 我更喜欢closest因为如果你的标记发生变化,它就不那么容易破解了。

Also, note that if you click on an anchor child of the last sibling <div> , the next() call will not produce any element. 另请注意,如果单击最后一个兄弟<div>的锚子项,则next()调用将不会生成任何元素。

Have you tried using parent ? 你尝试过使用父母吗?

Something like $(this).parent().next(); $(this).parent().next();

To get the 'uncle', you need to first get the parent, then the sibling. 为了得到'叔叔',你需要先得到父母,然后是兄弟姐妹。

$(this).parent('div').next('div')

Or, if the a is nested in other elements, you can use closest to get the parent div . 或者,如果a嵌套在其他元素中,则可以使用closest来获取父div

$(this).closest('div').next('div')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM