2013-07-04 20 views
4
$('.metro_menu_button').data('oldColor', $(this).css('background-color')); 

$('.metro_menu_button').hover(function() { 
    $(this).stop().animate({ 
     backgroundColor: '#303030' 
    }, 300); 

}, function() { 

    $(this).stop().animate({ 
     backgroundColor: $(this).data('oldColor') 
    }, 300); 

}); 

至於標題搜索「的backgroundColor」,上面的jQuery代碼(這是在DOM準備執行)將返回該錯誤jQuery的錯誤:遺漏的類型錯誤:不能使用「在」運營商在不確定的

Uncaught TypeError: Cannot use 'in' operator to search for 'backgroundColor' in undefined

這是爲什麼?我究竟做錯了什麼?


我試圖做一個按鈕,當懸停,改變顏色,當鼠標離開時,回到原來的顏色。我無法對這些值進行硬編碼:我需要這種靈活性,並且自己記住舊的背景顏色。下面的代碼工作正常,但是,如果我將鼠標移入和移出太快,它將「忘記」原始顏色。

$('.metro_menu_button').hover(function() { 

    $(this).data('oldColor', $(this).css('background-color')); 

    $(this).stop().animate({ 
     backgroundColor: '#303030' 
    }, 300); 

}, function() { 

    $(this).stop().animate({ 
     backgroundColor: $(this).data('oldColor') 
    }, 300); 

}); 

我需要保存oldColor上domready中,不是每次鼠標中獲得。換句話說,我需要使用的第一個代碼,但是這是引發錯誤。我能做什麼?

回答

5

您可以使用jQuery的「每個」功能:

$('.metro_menu_button').each(function() { 
    $(this).data('oldColor', $(this).css('background-color')); 
}); 

的「每個」應爲每個匹配節點運行此;你的原創可能不會有'這'的正確價值。

+0

非常感謝,我認爲類選擇器足以對所有元素執行操作:沒有考慮每個循環。 – Saturnix

相關問題