【发布时间】:2013-07-03 02:00:24
【问题描述】:
下面是我为动画导航方案编写的一些 jQuery 代码。
当我像这样写出来进行测试时,代码运行良好:
$("#about").click(function(e) {
e.preventDefault();
if ( !$(".current").hasClass("about") ){
$("body").css("overflow-x","hidden");
$(".current").animate({left:'-1500px'}, 500).slideUp(500);
$(".about").animate({left:'+3000px'}, 1).delay(500).slideDown();
$(".about").animate({left:'0px'}, 500, function(){
$(".current").removeClass("current");
$(".about").addClass("current");
$("body").css("overflow-x","visible");
});
}
});
但是当我尝试将它放入循环并在 jquery 选择器中使用变量时,它停止工作。
sections 数组中的每个字符串对应一个锚标记的 id 及其匹配的 div 元素的类。
它一直运行到第 7 行,但以 $("."+sections[i]) 开头的第 8 行和第 9 行不起作用。
var sections = ["about","photography","contact"];
for (var i=0; i<sections.length; i++) {
$("#"+sections[i]).click(function(e) {
e.preventDefault();
if ( !$(".current").hasClass(sections[i]) ){
$("body").css("overflow-x","hidden");
$(".current").animate({left:'-1500px'}, 500).slideUp(500);
$("."+sections[i]).animate({left:'+3000px'}, 1).delay(500).slideDown();
$("."+sections[i]).animate({left:'0px'}, 500, function(){
$(".current").removeClass("current");
$("."+sections[i]).addClass("current");
$("body").css("overflow-x","visible");
});
}
});
}
console.log( $("."+sections[i]).attr("class") ) 给我未定义。我认为问题出在选择器上,但我不知道它是什么。 id 选择器似乎工作正常,只是类选择器不行。任何建议表示赞赏!
【问题讨论】:
-
console.log($("."+sections[i]))输出什么?它应该告诉您选择器是什么以及长度(以及许多其他内容)。 -
console.log($("."+sections[i]))返回[prevObject: x.fn.x.init[1], context: document, selector: ".undefined", jquery: "1.10.1", constructor: function…] context: document length: 0 prevObject: x.fn.x.init[1] selector: ".undefined" __proto__: Object[0]我得到了运行代码并给出了下面的答案,但我仍然想弄清楚为什么它一开始就不起作用,因为我刚刚开始jQuery
标签: jquery arrays for-loop jquery-selectors