我对编写自己的jquery函数非常陌生,我发现调试它非常困难,因为错误消息在放到google中时没有太大帮助。
我有一个页面锚点的导航菜单,当单击每个锚点时,屏幕滚动到锚点,元素将根据哪一个而改变颜色,悬停颜色也将改变。真的很简单,我觉得。
滚动总是工作,动画工作偶尔和悬停作品放通常我必须点击链接两次。return false仅在您单击的第一个链接上有效。
这使用scrollTo和动画颜色插件。
有人能告诉我我哪里做错了吗?
$(".scrolltoanchor").click(function() {
$('a').removeClass('selected');
$(this).addClass('selected');
$.scrollTo($($(this).attr("href")), {
duration: 750
});
switch ($(this).attr("id")) {
case 'personal':
$('.scrolltoanchor').animate({color: '#E4D8B8'});
$(".scrolltoanchor").hover(
function() {
$(this).css('color', 'blue');
},function(){
$(this).css('color', '#E4D8B8');
});
break;
case 'achievements':
$('.scrolltoanchor').animate({color: '#ffffff'});
$(".scrolltoanchor").hover(
function() {
$(this).css('color', 'red');
},function(){
$(this).css('color', '#ffffff');
});
break;
case 'skills':
$('.scrolltoanchor').animate({color: '#dddddd'});
$(".scrolltoanchor").hover(
function() {
$(this).css('color', 'orange');
},function(){
$(this).css('color', '#ffffff');
});
break;
}
return false;
});很抱歉,我要求被填鸭式喂养,但我遵循了我所学到的我认为是正确的语法。是不是有什么我应该知道的事情让它不能像我预期的那样工作了?
编辑:对不起,我忘记了,我在(平均)每秒点击一次scrolltoanchor锚点链接时收到这个错误。
未捕获的TypeError:无法读取未定义的属性“0”
我找不到真正的模式。有时它似乎只发生在以前没有点击过的页面上,有时则没有。谢谢
发布于 2011-12-09 08:56:13
你采取了错误的方法。
您应该绑定一次悬停处理程序,并根据单击的颜色来决定颜色。
最简单的方法可能是将颜色数据存储在查找表中,其中键是元素的ID。
var ids = {
personal: {
over:'blue',
out:'#E4D8B8'
},
achievements: {
over:'red',
out:'#ffffff'
},
skills: {
over:'orange',
out:'#dddddd'
}
};
var current = ids.personal;然后绑定一次处理程序,并使用单击的处理程序的id来设置current颜色集。
var scroll_anchors = $(".scrolltoanchor");
scroll_anchors.hover( function() {
$(this).css( 'color', current.over );
},function(){
$(this).css( 'color', current.out );
});
scroll_anchors.click(function() {
$('a.selected').removeClass('selected');
$(this).addClass('selected');
$.scrollTo($($(this).attr("href")), { duration: 750 });
current = ids[ this.id ]; // set the current color set based on the ID
scroll_anchors.animate({ color: current.out });
return false;
});发布于 2011-12-09 08:52:15
当您多次调用.hover()时,您并没有删除旧的事件处理程序,只是添加了一个新的事件处理程序。每次都会调用每个处理程序。你需要先调用.unbind("hover"):
$(".scrolltoanchor").unbind("hover").hover(function () {
...
});您还可以绑定到switch语句之外的悬停,以消除一些代码重复:
$(".scrolltoanchor").click(function () {
$('a').removeClass('selected');
$(this).addClass('selected');
$.scrollTo($(this.href), {
duration: 750
});
var off, on;
switch (this.id) {
case 'personal':
off = '#E4D8B8';
on = 'blue';
break;
case 'achievements':
off = '#ffffff';
on = 'red';
break;
case 'skills':
off = '#dddddd';
on = 'orange';
break;
}
$('.scrolltoanchor')
.animate({ color: off })
.unbind("hover")
.hover(function () {
$(this).css('color', on);
}, function () {
$(this).css('color', off);
});
return false;
});https://stackoverflow.com/questions/8439731
复制相似问题