jquery how to change only one parent closeset <A> tag on hover

别等时光非礼了梦想. 提交于 2019-12-24 06:35:33

问题


I asked similar question here

jquery how to change only one parent on hover

But it's not what I want. so , I re-code and post it again here

I would like to change only one parent on <a> when I hover over <p> tags. The code is:

$('.hover').each(function () {
 $(this).parent().hover(function () {
        $('p').parent(this).css('background-color','red');
    }, function () {
        $('p').parent(this).css('background-color','black');
 });
});

And the HTML is:

<ul>
   <li><a href='#'>1</a> <p class='hover'>A</p></li>
   <li><a href='#'>2</a> <p class='hover'>B</p></li>
   <li><a href='#'>3</a> <p class='hover'>B</p></li>
   <li><a href='#'>4</a> <p class='hover'>X</p></li>
   <li><a href='#'>5</a> <p class='hover'>Y</p></li>
   <li><a href='#'>6</a> <p class='hover'>Z</p></li>
</ul>

What i want is when i hover "A" and "1" is change and other not change and when i hover on "b" and "2" is change other not change also

sorry , im really new in jquery.


回答1:


there is no need of .each, use .prev

$('.hover').hover(function () {
        $(this).prev('a').css('background-color','red');
    }, function () {
        $(this).prev('a').css('background-color','yellow');
 });

alternative : you can use .parent().children('a') OR .siblings('a') instead of .prev('a')

​ Demo

Update

If you want to use .each ( as you mentioned in comment ) then do below.

$('.hover').each(function () {
 $(this).parent().hover(function () {
        $(this).children('a').css('background-color','red');
    }, function () {
        $(this).children('a').css('background-color','yellow');
 });
});

Demo using .each




回答2:


Using closest('a') here doesn't work because closest navigates up the dom tree, not to siblings. Navigating using .parent('li').find('a') will find the associated 'a'

Also, as far as I can tell, you just want the hover handlers on the <p>, so no need for each.

$('.hover').hover(function () {
        $(this).parent('li').find('a').css('background-color','red');
    }, function () {
        $(this).parent('li').find('a').css('background-color','black');
 });

Fiddle here: http://jsfiddle.net/U4n2T/16/



来源:https://stackoverflow.com/questions/12418179/jquery-how-to-change-only-one-parent-closeset-a-tag-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!