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

时间:2013-07-04 11:37:18

标签: jquery jquery-ui animation

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

});

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

  

未捕获的TypeError:无法使用'in'运算符进行搜索   未定义的'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);

});

我需要在DOMReady上保存oldColor,而不是每次鼠标进入时都保存。换句话说,我需要使用第一个代码,但这会引发错误。我该怎么办?

1 个答案:

答案 0 :(得分:5)

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

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

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