jquery 匹配触发事件的 div 的子级

标签 jquery jquery-selectors

我正在尝试创建一个画廊/轮播小部件,如果该特定图像有鼠标悬停事件,它将在每个图像上显示一个 div。 到目前为止,我有这段代码来显示 div:

$(document).ready(function(){

  $(".background").mouseover(function(){
    $(".info").show(1500);
  });
  $(".background").mouseout(function(){
     $(".info").hide(1500);
  });
});

和 html 方面

<div id="wrapper">
<div id="slides">
    <ul>
         <li>
        <img class="background" src="images/1.png" width="240" height="240"/>
             <div class="info">Thats the info of this image</div>
    </li>
        <li>
               <img src="images/ogm.png" width="240" height="240"/>
                    <div class="info">Thats the info of this image</div>
        </li>
        <li><img src="images/2.jpg" width="240" height="240"/>
                 <div class="info">Thats the info of this image</div>
        </li>
        <li>
            <img src="images/3.png" width="240" height="240"/>
                 <div class="info">Thats the info of this image</div>
        </li>
        <li>
            <img src="images/4.png" width="240" height="240"/>
                 <div class="info">Thats the info of this image</div>
       </li>
        <li>
            <img src="images/5.png" width="240" height="240"/>
                 <div class="info">Thats the info of this image</div>
        </li>
    </ul>
</div>

info 是 div,background 是图像的类

正如预期的那样,当鼠标悬停在任何图像上时,所有信息 div 都会匹配并显示。

是否可以只显示触发鼠标悬停的背景图像中包含的特定信息 div?

最佳答案

您提供给 jQuery 绑定(bind)函数的回调作为引发事件的元素的上下文 (this) 提供。因此,您可以从 $(this) 搜索 '.info' :

$(document).ready(function(){
  $(".background").mouseover(function(){
    $(this).parent().find(".info").show(1500);
  });
  $(".background").mouseout(function(){
     $(this).parent().find(".info").hide(1500);
  });
});

或者(雷纳托的建议):

$(document).ready(function(){
  $(".background").mouseover(function(){
    $(this).sibblings(".info").show(1500);
  });
  $(".background").mouseout(function(){
     $(this).sibblings(".info").hide(1500);
  });
});

请注意,jQuery 允许链接:

$(document).ready(function(){
  $(".background").mouseover(function(){
    $(this).parent().find(".info").show(1500);
  }).mouseout(function(){
     $(this).parent().find(".info").hide(1500);
  });
});

另请注意,大多数情况下您需要 mouseentermouseleave而不是 mouseovermouseout

关于jquery 匹配触发事件的 div 的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761519/

相关文章:

javascript - 如何使用 jquery 查找并选择所有具有数据属性并以特定单词开头的元素?

jQuery:选择器困惑

jQuery - 将多个选择器缓存到一个变量?

jquery - 如何查看是否点击同一个元素两次? jQuery

jquery - 如何修复类似于 Bootstrap 站点的侧边栏?

javascript - 如果弹出窗口被打开,则禁止刷新

javascript - jQuery - 名称属性中的方括号出错

javascript - Bootstrap 下拉菜单嵌套在表单 : tabindex breaks on enter 中

javascript - 如何始终显示在 HTML Select 中选择的第一个选项?

javascript - TypeError : this. 元素为空,Rails with Judge gem