jQuery错误:未捕获TypeError:无法使用'in'运算符在undefined中搜索'backgroundColor'

Sat*_*nix 4 jquery animation jquery-ui

$('.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);

});
Run Code Online (Sandbox Code Playgroud)

至于标题,上面的jQuery代码(在DOM就绪时执行)返回此错误

未捕获的TypeError:无法使用'in'运算符在undefined中搜索'backgroundColor'

为什么是这样?我究竟做错了什么?


我正在尝试做一个按钮,它在悬停时会改变颜色,当鼠标离开时,会恢复原来的颜色.我无法对这些值进行硬编码:我需要灵活处理,并且要记住旧的背景颜色.下面的代码工作正常但是,如果我将鼠标移入和移出太快,它将"忘记"原始颜色.

$('.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);

});
Run Code Online (Sandbox Code Playgroud)

我需要保存oldColorDOMReady,而不是每次鼠标进入.换句话说,我需要使用第一个代码,但这是抛出错误.我能做什么?

Adr*_*agg 5

您可以使用jQuery的'each'功能:

$('.metro_menu_button').each(function() {
    $(this).data('oldColor', $(this).css('background-color'));
});
Run Code Online (Sandbox Code Playgroud)

'each'应该为每个匹配节点运行它; 您的原件可能没有'this'的正确值.