基本的jQuery-无法使用hover()来定位特定的元素

时间:2012-11-12 00:53:31

标签: jquery this each

我有一系列项目:

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,但应该有一个更简单的方法来做这个......

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用$(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/