jquery how to change only one parent on hover

无人久伴 提交于 2019-12-10 14:34:47

问题


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');
    });


来源:https://stackoverflow.com/questions/12406094/jquery-how-to-change-only-one-parent-on-hover

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