Ok so I'm currently working on a page where ill have two elements, the parent and the child.
<div id="parent">Hi
<span class="child">Bye&l开发者_StackOverflow社区t;/class>
</div>
What I want is to have the child element displayed when the parent element is hovered over. So I created a function in jQuery that will let me do exactly that.
function icondisplay(parentId){
$(parentId).mouseenter(function() {
$('.child').show();
});
$(hover).mouseleave(function() {
$('.child').hide();
});
}
The problem I'm having is that there are multiple parents within the page with different IDs, but the child elements are all the same class. So when I hover over any parent element, all of the child elements are displayed at once. How can I make only the child element within the parent display, without going through and giving each child element a unique class/id then changing my function?
Thank you
Don't use jQuery, use CSS.
.child {
display: none;
}
*:hover > .child {
display: inline;
}
I hesitate to add this, because the CSS approach makes so much more sense, but here we go: If you must use jQuery, use :has( > .child)
:
$("div:has(> .child)").hover(function()
$("> .child", this).show();
}, function() {
$("> .child", this).hide();
});
You simply need to change how you are selecting the parents and then selecting the childs:
$('.parentElement').hover(function()
{
$(this).find('.child').show();
}, function()
{
$(this).find('.child').hide();
});
I would assume something like this: http://jsfiddle.net/ex2nJ/1/ would solve your problem. for $("div")
you can just put in your function to find whatever parent ID. However, you may not even need to.
You can do this with CSS. Assume HTML something like:
<div class="parent">
<div class="child"></div>
</div>
You can do:
.child { display: none; }
.parent:hover > .child { display: inline; }
http://api.jquery.com/child-selector/
$(parentId).mouseenter(function(){
$(parentId > '.child').show();
});
that would do
$(this).find('.child')
or
$('.child', this)
Change it like that below
$(parentId).mouseenter(function() {
$(this).find('.child').show();
});
Sure can
$('#parent').hover(function(){
$(this).children().show();
},function(){
$(this).children().hide();
});
http://jsfiddle.net/NkAnR/
And make sure to fix your closing span
</class>
tag
精彩评论