嵌入的jQuery变量不正确

这里的回调函数不起作用。我想我正在使用startColor变量。 注意:这需要jQuery UI。
$("a").hover(function() { 
    var startColor = $(this).css("color");
    $(this).stop().animate({ color: "#54a888"}, 350);
    },function() {  
    $(this).stop().animate({ color: " + startColor + "}, 350);
});
多谢你们。我实际上是在尝试重构这段代码:
$("nav ul li a, aside ul li a").hover(function() {  
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
    },function() {  
    $(this).stop().animate({ color: "#5944b2"}, 350);  //Start color
});
$("h5#logo a, button").hover(function() {  
    $(this).stop().animate({ backgroundColor: "#54a888"}, 350);
    },function() {  
    $(this).stop().animate({ backgroundColor: "#000000"}, 350);
});
    $("h3 a").hover(function() {  
    $(this).stop().animate({ color: "#54a888"}, 350);
    },function() {  
    $(this).stop().animate({ color: "#000000"}, 350);
});
我有不同的起始颜色和不同的属性,我想要动画。似乎比重复相同的代码3次更好的解决方案。     
已邀请:
在两个函数之外声明它,并删除
" + + "
var startColor;

$("a").hover(function() { 
    startColor = $(this).css("color");
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
},function() {  
    $(this).stop().animate({ color: startColor}, 350);  //Start color  
}); 
...或者更好的是,使用
.data()
记住该特定元素的颜色:
$("a").hover(function() { 
    if( !$(this).data( 'startColor' ) ) {
        $(this).data( 'startColor', $(this).css("color") );
    }
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
},function() {  
    $(this).stop().animate({ color: $(this).data('startColor')}, 350);  
}); 
...或者如果所有链接的颜色恰好相同,只需获取一次,然后重用该值。因为你正在处理动画,它实际上可能更安全。
var startColor = $(a).css("color");

$("a").hover(function() { 
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
},function() {  
    $(this).stop().animate({ color: startColor}, 350);  //Start color  
}); 
编辑:根据您更新的问题,看起来您正在尝试做一些代码缩减。看起来他们之间存在足够的差异,试图合并会很复杂,以至于你可能会得到更多的代码。 减少的一种方法是将你的
hover()
处理程序改为接受1个函数而不是2:
$("h3 a").hover(function( e ) {  
    $(this).stop().animate({ color: e.type == 'mouseenter' ? "#54a888" : "#000000"}, 350);
});
稍微缩短一点。 另一个选择(因为你使用jQueryUI我假设)将动画一个
toggleClass
(虽然我认为它可能在最新版本的UI中被打破)。
$("h3 a,nav ul li a, aside ul li a,nav ul li a, aside ul li a").hover(function( e ) {  
    $(this).stop().toggleClass('hover', 350);
});
然后在CSS中:
h3 a.hover {
    color:#000000;
}

nav ul li a.hover, aside ul li a.hover {
    color:#54a888;
}

// etc...
...再次意识到我认为它可能在最新版本中被破坏了,你需要进行测试,因为它有时候会变得很脆弱。     
" + + "
没有意义。只是用
$(this).stop().animate({ color: startColor}, 350);  //Start color  });  
    
您在一个回调中创建一个局部变量,并尝试在另一个回调中使用它。 相反,您应该使用
$.data
存储旧颜色。 另外,不要在变量周围加上引号;这使它成为一个字符串。     

要回复问题请先登录注册