2011-02-26 110 views
2

我想是這樣的幫助動畫孩子的div JQuery的

jQuery(document).ready(function($){ 
    $('nav ul li').hover(
     function() { 
      $('this.menu1bar').animate({ backgroundColor: "#95c938" }, "fast"); 
      $('this.menu2bar').animate({ backgroundColor: "#95c938" }, "fast"); 
     }, 
     function() { 
      $('this.menu1bar').animate({ backgroundColor: "#a99672" }, "fast"); 
      $('this.menu2bar').animate({ backgroundColor: "#a99672" }, "fast"); 
     } 
    ); 
    }); 

這段代碼的目的是動畫孩子的div .menu1bar和.menu2bar任何人都可以用此步驟的幫助,代碼適用於所有UL的兒童div,但我只想要LI懸停事件的孩子。

+2

這是你的實際代碼嗎? '$('this.menu1bar')'不應該選擇任何元素,因爲不存在'HTML元素'''。 – 2011-02-26 19:43:23

+1

@Matt:我只是坐在這看了兩分鐘,想'這肯定不行',但後來我被「代碼適用於UL的所有兒童div」聲明所困惑。謝謝你緩解我困擾的心態...... =)+1 – 2011-02-26 19:44:44

+0

@大衛:是的,問題的措辭傷害了我的頭。 – 2011-02-26 19:45:21

回答

3

這應該工作:

jQuery(document).ready(function($){ 
    $('#nav ul li').hover(
     function() { 
      $(this).find('.menu1bar,.menu2bar').animate({ backgroundColor: "#95c938" }, "fast"); 
     }, 
     function() { 
      $(this).find('.menu1bar,.menu2bar').animate({ backgroundColor: "#a99672" }, "fast"); 
     } 
    ); 
}); 
0

請出示你的HTML標記。我認爲,這個問題可能會在以下...

$('this.menu1bar') 

嘗試

$(this).find('.menu1bar') 
2

嘗試使用children()選擇一個特定的元素。事情是這樣的:

$('this').children('.menu1bar').animate({ backgroundColor: "#95c938" }, "fast"); 

編輯:

當然,你也可以使用find(),但有一個區別:

  • find()會搜索所有的孩子,所有 水平,也孫子。
  • 孩子()只搜索第一級 孩子。
+0

那麼在兒童()中應該會更快? – Emmanuel 2011-02-26 19:52:08

+0

@Emmanuel我這麼認爲,從來沒有測試過......這也取決於你想要什麼。如果你想匹配所有級別的孩子,你必須使用find(),否則children()就夠用了。順便說一下,這對於一些測試是一個很好的主題,我會牢記它。 – Ray 2011-02-26 19:53:52