简体   繁体   English

如何将$(this)与jquery一起使用以更改div父元素上的元素?

[英]How to use $(this) with jquery to change an element that is on the parent of a div?

I'm trying to do a simple thing with JQuery but I struggle to understand what I should do. 我正在尝试使用JQuery做简单的事情,但是我很难理解我应该做什么。

What I'd like to do is when .overlay-detail is hovered $(this).closest('p img:first-child').css('display', 'none') else ('display', 'block') 我想做的是将.overlay-detail悬停在$(this).closest('p img:first-child').css('display', 'none') else ('display', 'block')

(see html to understand) (请参见html了解)

<div id="block-views-quipe-block">

<div class="field-content">
   <p>
     <img alt="" src="/sites/default/files/_CA17330lr.jpg">
     <img alt="" src="/sites/default/files/_CA17322lr.jpg">
   </p>

   <div class="overlay-detail">
     <p>John Doe 1</p>
     <p>job 1</p>
   </div>
</div>  

<div class="field-content">
   <p>
     <img alt="" src="/sites/default/files/_CA17330lr.jpg">
     <img alt="" src="/sites/default/files/_CA17322lr.jpg">
   </p>

   <div class="overlay-detail">
     <p>John Doe 2</p>
     <p>job 2</p>
   </div>
</div>  

...

</div>

Here is what I thought doing : 这是我的想法:

$("#block-views-quipe-block .overlay-detail").hover(function(){
  $(this).closest('p img:first-child').css("display", "none");
}, function(){
   $(this).closest('p img:nth-child(2)').css("display", "block");
});

What am I doing wrong ? 我究竟做错了什么 ?

The issue is because closest() looks for parent elements, whereas the p is a sibling. 问题是因为closest()寻找父元素,而p是同级元素。 Use prev() instead to get the p , then find() to get the child img : 使用prev()来获取p ,然后使用find()来获取子img

$("#block-views-quipe-block .overlay-detail").hover(function(){
  $(this).prev('p').find('img:first-child').hide();
}, function(){
  $(this).prev('p').find('img:nth-child(2)').show();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM