【问题标题】:Is it possible to combine $(this) with a non child element?是否可以将 $(this) 与非子元素结合使用?
【发布时间】:2012-09-27 16:43:46
【问题描述】:

我有一个<divs> 的列表与同一类。每个<li> 中有两个<divs>。当用户将鼠标悬停在另一个 <div> 上时,我想隐藏一个 <div>

我遇到的问题是,当我使用以下代码时,当我将鼠标悬停在任何带有“.div_1”类的<div> 上时,每个带有“.div_2”类的<div> 都会被隐藏。

我想要它,所以当用户将鼠标悬停在特定<li> 中的类“.div_1”上时,只有类“.div_2”的<div> 被隐藏

我无法更改标记或类,并且想知道如何实现这一点。我可以将$(this) 与“.div_2”结合起来吗?

<li>
<div class="div_1"></div>
<div class="div_2"></div>
</li>    
<li>
<div class="div_1"></div>
<div class="div_2"></div>
</li> 
... 

$(document).ready(function(){
    // MEDIA GALLERY HOVER //

        $(".div_1").hover(
          function () { $(".div_2").hide(); },
          function () { $(".div_2").show(); }
        );

})

【问题讨论】:

    标签: jquery hide this show-hide


    【解决方案1】:
    $(document).ready(function(){
        // MEDIA GALLERY HOVER //
    
            $(".div_1").hover(
              function () { $(this).siblings(".div_2").hide(); },
              function () { $(this).siblings(".div_2").show(); }
            );
    
    })
    

    或者让你的代码更短 - DEMO

    $(document).ready(function(){
        $(".div_1").on("mouseover mouseout", function() {
            $(this).siblings(".div_2").toggle();
        });
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用next 方法,它选择元素的下一个兄弟元素或siblings 方法。

      $(".div_1").hover(
          function () { $(this).next().hide(); },
          function () { $(this).next().show(); }
      );
      

      【讨论】:

        【解决方案3】:
        $('.div1').on('mouseover',function() { $(this).siblings('.div2').css('display','none'); });
        

        【讨论】:

          【解决方案4】:
              $(".div_1").hover(
                function () { $(this).siblings(".div_2").hide(); },
                function () { $(this).siblings(".div_2").show(); }
              );
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-02-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-06-07
            • 2015-01-02
            • 2019-02-15
            • 1970-01-01
            相关资源
            最近更新 更多