jquery如何更改只有一个父悬停 [英] jquery how to change only one parent on hover

查看:122
本文介绍了jquery如何更改只有一个父悬停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将鼠标悬停在< p> 标签上时,我只想更改一个父级。代码是:
$ b $ pre $ $('。hover')。each(function(){
$(this) .parent()。hover(function(){
$('p')。parent(this).css('font-size','30px');
},function(){
$('p')。parent(this).css('font-size','10px');
});
});

和HTML是:

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

当我将鼠标悬停在xxxx上时,我想要1和xxxx 2和yyyy什么都不做,当我把鼠标悬停在yyyy上时,我想要2和yyyy改变,但1和xxxx什么都不做。



我是jQuery的新手。

解决方案

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

您不必使用每个循环来添加悬停。如果您选择了多个元素,它会将事件应用于所有元素。



说了这些,我稍微优化了您的代码。



我已经在段落的父级上添加了悬停,就像您一样。通过在事件回调中使用 $(this),我实际上可以选择histed元素并在该元素上应用样式。



因为我希望字体大小适用于该段落,所以我先选择所需的小孩。






以上总结
$ b


  • 查找段落元素( $('p.hover')

  • 获取它的父项, li 元素( .parent()

  • 应用悬停事件( .hover()



调用hover事件后:


  • 获取当前元素( $(this )

  • 找到内部段落( .children('p')

  • 应用样式


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.

解决方案

$('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

这篇关于jquery如何更改只有一个父悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆