jQuery select this child
<ul>
<li class="hoverMe"><div class="secret">Haha</div></li>
<li class="hoverMe"><div class="secret">Blabla</div></li>
<li class="hoverMe"><div class="secret"开发者_如何学JAVA>Tada</div></li>
</ul>
Secred divs are hidden in css:
.secret {
display: none;
}
I want to display the secret child of "hoverMe" after hovering "hoverMe' (so when user hovers link number one he sees "Haha", nubmer two "Blabla" etc.).
I've tried this code and it doesn't work. I've been trying replacing "next" with "child(ren)" etc., but nothing. Any ideas?
jQuery().ready(function() {
jQuery('.hoverMe').hover(function(){
jQuery(this).next('.secret').Toggle();
});
});
The strange thing is (this).children() toggles all children, but when I try with (this).children('.secret') it doesn't do a thing.
hover() can bind two handlers:
$('.hoverMe').hover(function(){
$(this).children().show();
}, function(){
$(this).children().hide();
})
or
$('.hoverMe').hover(function(){
$(this).find('.secret').show();
}, function(){
$(this).find('.secret').hide();
})
or, as @Felix Kling kindly noticed, it can bind only one handle with:
$('.hoverMe').hover(
$(this).find('.secret').toggle();
)
Your .hoverme
s are empty (have a height of 0) when .secret
is not displayed, so there is nothing to hover over.
You'll need to use visibility: hidden
/ visibility: visible
instead
.secret {
visibility:hidden;
}
jQuery().ready(function() {
$(".hoverMe").hover(function () {
$(this).find(".secret").css("visibility", "visible");
}, function () {
$(this).find(".secret").css("visibility", "hidden");
});
});
Example: http://jsfiddle.net/bM7f2/
http://api.jquery.com/children/
jQuery(this).children('.secret')[0]
Oh you tried that. never mind.
$(function(){
$("ul li.hoverMe").hover(function(){
$(this).children("div.secret").show();
},
function(){
$(this).children("div.secret").hide();
});
});
jQuery().ready(function() {
jQuery('.hoverMe').hover(function(){
jQuery(this).children('.secret').**t**oggle();
});
});
JS is case sensitive
- Use
children
. toggle
needs to start with a small letter.- Important: You need other "visible" content in the list element. Otherwise it takes up no space and there is nothing you can hover over. At least you would have to add an
. As you can see in the demo, I added those. If you remove it, it won't work anymore.
So it should be:
jQuery('.hoverMe').hover(function(){
jQuery(this).children('.secret').toggle();
});
Your ready handler is also wrong, must be:
jQuery(document).ready(function() {
//...
});
DEMO
If it ever happens to you and nothing seem to work try adding another child() to the chain, or at least check your markup to make sure that your parent element is not really a GRANDparent.
The answer was:
$(this).children().children().show();
精彩评论