问题
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