Select sibling of parent on hover with jQuery

2019-06-20 05:43发布

I'm trying to change the css of .target that is the sibling of the parent of .hover. Can't seem to get this code to work - I'm not sure if I need $(this) at the beginning of my function, or $('.target')... I think it might be .target because that is what I'm changing the css of with .css().

<script type="text/javascript">
$(document).ready(function() {
    $('.hover').hover(
        function(){
            $(this).parent().siblings('.target').css('display', 'inline');
        },
        function(){
            $(this).parent().siblings('.target').css('display', 'none');
        }
    );
});
</script>

And here is my hunch (which also doesn't work):

$('.target').parent(this).sibling().css('display', 'inline');

And here is html

<div class="target" style="display: none;">
</div>
<div>
    <span class="hover">Hover</span>
</div>

EDIT----------------- It seems that it doesn't work when a span is class="hover".

EDIT numero dos -------------------- It seems that I had my <span> two parents deep and needed .parent().parent() Thanks.

3条回答
Viruses.
2楼-- · 2019-06-20 05:47

Andy, Check this fiddle out, you seem to have the correct code in the first sample that you posted. If you could post your html, we might have a better time helping out. http://jsfiddle.net/nKtzB/3/

查看更多
干净又极端
3楼-- · 2019-06-20 06:00

Try using display:block instead, if you are trying to do something with the block.

Your code is still fine, see: http://jsfiddle.net/Mx4ks/1/


Something else must be wrong.. Try pasting your HTML too :)

See your own code in action here: http://jsfiddle.net/Mx4ks/

查看更多
\"骚年 ilove
4楼-- · 2019-06-20 06:01

Assuming your html is as you expect, and without seeing it I can't comment on improvements, this should work:

$('.target').parent().siblings('.target').css('display', 'inline');

Or, if the the .target element is the next sibling:

$('.target').parent().next('.target').css('display', 'inline');

Or, if the previous sibling (and from the html you posted it is the previous sibling):

$('.target').parent().prev('.target').css('display', 'inline');

References:

查看更多
登录 后发表回答