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?).
I want to use the same class name for all my content so I want to use only relative to $(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>
. .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.)
So I need to access the uncle div of the one I'm in? How would I do that -
Here's what I have been playing with so far:
js:
$(document).ready(function() {
$('.demo > .row').hide();
$('.demo > .box > a').click(function() {
$(this).next().slideToggle('fast')
.siblings('div:visible').slideUp('fast');
});
});
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. In this case, you need parent
followed by 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>
:
$(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.
Also, note that if you click on an anchor child of the last sibling <div>
, the next()
call will not produce any element.
Have you tried using parent?
Something like $(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
.
$(this).closest('div').next('div')
精彩评论