jquery how to change only one parent on hover

2019-06-22 06:55发布

问题:

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

$('.hover').each(function () {
    $(this).parent().hover(function () {
            $('p').parent(this).css('font-size','30px');
        }, function () {
            $('p').parent(this).css('font-size','10px');
    });
});

and the HTML is:

   <ul>
        <li>1 <p class='hover'>xxxx</p></li>
        <li>2 <p class='hover'>yyyy</p></li>
    </ul>

When I hover over "xxxx", I want "1" and "xxxx" to change but "2" and "yyyy" do nothing, and when I hover over "yyyy", I want "2" and "yyyy" to change but "1" and "xxxx" do nothing.

I'm new to jQuery.

回答1:

$('p.hover').parent().hover(function() {
    $(this).children('p').css('font-size','30px');
}, function () {
    $(this).children('p').css('font-size','10px');
});

You don't have to use an each loop to add the hovers. If you have multiple elements selected, it will apply the event on all elements.

Having that said, I slightly optimised your code.

I have added the hover on the paragraph's parent, just like you did. By using $(this) in the event's callback I can actually select the hovered element and apply styles on that element.

Because I want the font-size to apply on the paragraph, I select the desired child first.


Summing above up:

  • Find the paragraphs elements ($('p.hover'))
  • Get it's parent, the li element (.parent())
  • Apply the hover event (.hover())

Once the hover event is called:

  • Get current element ($(this))
  • Find the inner paragraph (.children('p'))
  • Apply styles


回答2:

You could use

$('p').closest('li').css('font-size','30px');


回答3:

Parent of <p> in your case is <li>. You need:

$('.hover').parent().parent().hover(
    function () {
        $(this).css('font-size','30px');
    }, function () {
        $(this).css('font-size','10px');
    });