I've been trying to bind a $.click
handler to a sibling element, but can't seem to find a way to properly select the element to animate. Here is the basic structure of the DOM tree that I'm working with:
<section id="a">
<div id="b" class="foo" draggable="true">
<header style="cursor:pointer;">1.</header>
<p class="foo">Bar</p>
</div>
<div id="c" class="foo" draggable="true">
<header style="cursor:pointer;">2.</header>
<p class="foo">Bar</p>
</div>
<!-- and so on... -->
</section>
Now, when a user clicks a <header>
, I would like the sibling <p>
to perform a jQuery.slideToggle()
. At this point, I have the following JavaScript, but to no avail:
$('header').click(function() {开发者_如何学JAVA
$(this).parent().children("p").slideToggle('slow');
// I also tried:
$(this).parent().children("p.foo").slideToggle('slow');
// but as I expected, there was no difference.
});
So to clarify, a very drawn-out version of this would be:
$('div#b.foo header').click(function(){
$('div#b.foo p.foo').slideToggle('slow');
});
$('div#c.foo header').click(function(){
$('div#c.foo p.foo').slideToggle('slow');
});
// ...
Please ask me to elaborate if this is not clear enough.
You can try
$('header').click(function() {
$(this).next().slideToggle('slow');
});
Live Example
.next
I resolved the issue by initializing the click handler on document ready. The solution is as follows:
$(document).ready(function() {
$('header').click(function() {
$(this).next().slideToggle('slow');
});
});
精彩评论