2012-11-12 100 views
1

我有一系列的項目:基本jQuery-不能得到懸停(),以針對特定元素

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,但應該有一個更簡單的方法來做到這一點...

謝謝。

回答

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/