【问题标题】:Basic jQuery- can't get hover( ) to target a specific element基本 jQuery - 无法让 hover() 定位特定元素
【发布时间】:2012-10-31 11:41:34
【问题描述】:

我有一系列物品:

http://imgur.com/ZWKI4

每个项目的结构如下:

        <div class="span3 item">
          <img class="itemImage" src="assets/img/bure.jpg">
          <div class="itemDescription">
            <p><span class="itemDescLabel">Title:</span> <script>document.write(title);</script></p>
            <p><span class="itemDescLabel">Price:</span> <script>document.write(price);</script></p>
            <p><span class="itemDescLabel">Source:</span> <script>document.write(source);</script></p>
          </div><!-- /itemDescription-->
        </div> <!-- /item--> 

这个想法是,当我将鼠标悬停在一个上时,应该显示它的描述。

当前发生的情况是,当我将鼠标悬停在一个上时,会显示所有项目的描述。

发生这种情况是因为我正在像这样应用悬停:

    $(document).ready(function() {
        $('.item').hover(
          function() {
          $('.itemDescription').show();
            }, 
          function() {
          $('.itemDescription').hide();
        });//end hover    
      });//end ready

我试过这样做:

  $(document).ready(function() {
    $('.item').hover(
      function() {
      $(this).next('.itemDescription').show();
        }, 
        function() {
      $(this).next('.itemDescription').hide();
    });//end hover 
  });//end ready

还有这个:

  $(document).ready(function() {
    $('.item').each(function() {
      $(this).hover(
        function() {
      $(this).next('.itemDescription').show();
        }, 
        function() {
      $(this).next('.itemDescription').hide();
      });//end hover
    });//end each
  });//end ready

这两种方法都没有奏效。

我做错了什么?我知道我可以为每个项目指定一个不同的 ID,但应该有更简单的方法来执行此操作...

谢谢。

【问题讨论】:

    标签: jquery this each


    【解决方案1】:

    您可以使用$(selector, context)find 方法。

    $(document).ready(function() {
        $('.item').hover(function() {
            $('.itemDescription', this).show();
            // $(this).find('.itemDescription').show();
        }, function() {
            $('.itemDescription', this).hide();
        });
    }); 
    

    next 选择下一个兄弟元素,在您的标记中,itemDescriptionitem 元素的后代,而不是兄弟元素。

    你也可以使用toggle方法。

    $('.item').hover(function() {
        $('.itemDescription', this).toggle();
    });
    

    http://jsfiddle.net/pvFN9/

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 2018-08-30
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多