我在for循环中遇到了一些问题:
var wide = "700px";
var flat = "5px";
var pages = new Array("home","links","aktuell","kontakt");
for(var i=0;i<pages.length;i++) {
$("."+pages[i]).bind("click", function() {
for(var j=0;j<pages.length;j++) {
var width;
if(pages[j] != pages[i])
width = flat;
else
width = wide;
$("#"+pages[j]).animate({width: width}, "slow");
}
});
$("#"+pages[i]).bind("click", function() {
for(var k=0;k<pages.length;k++) {
var width;
if(pages[k] != pages[i])
width = flat;
else
width = wide;
$("#"+pages[k]).animate({width: width}, "slow");
}
});
}
实际上它应该产生以下输出,但为什么不呢?
$(".home").bind("click", function() {
$("#home").animate({width: wide}, "slow");
$("#links").animate({width: flat}, "slow");
$("#aktuell").animate({width: flat}, "slow");
$("#kontakt").animate({width: flat}, "slow");
});
$("#home").bind("click", function() {
$("#home").animate({width: wide}, "slow");
$("#links").animate({width: flat}, "slow");
$("#aktuell").animate({width: flat}, "slow");
$("#kontakt").animate({width: flat}, "slow");
});
$(".links").bind("click", function() {
$("#links").animate({width: wide}, "slow");
$("#home").animate({width: flat}, "slow");
$("#aktuell").animate({width: flat}, "slow");
$("#kontakt").animate({width: flat}, "slow");
});
$("#links").bind("click", function() {
$("#links").animate({width: wide}, "slow");
$("#home").animate({width: flat}, "slow");
$("#aktuell").animate({width: flat}, "slow");
$("#kontakt").animate({width: flat}, "slow");
});
$(".aktuell").bind("click", function() {
$("#links").animate({width: flat}, "slow");
$("#home").animate({width: flat}, "slow");
$("#aktuell").animate({width: wide}, "slow");
$("#kontakt").animate({width: flat}, "slow");
});
$("#aktuell").bind("click", function() {
$("#links").animate({width: flat}, "slow");
$("#home").animate({width: flat}, "slow");
$("#aktuell").animate({width: wide}, "slow");
$("#kontakt").animate({width: flat}, "slow");
});
$(".kontakt").bind("click", function() {
$("#links").animate({width: flat}, "slow");
$("#home").animate({width: flat}, "slow");
$("#aktuell").animate({width: flat}, "slow");
$("#kontakt").animate({width: wide}, "slow");
});
$("#kontakt").bind("click", function() {
$("#links").animate({width: flat}, "slow");
$("#home").animate({width: flat}, "slow");
$("#aktuell").animate({width: flat}, "slow");
$("#kontakt").animate({width: wide}, "slow");
});
有人能找到错误吗?我试图将它全部作为输出并且它工作正常但是当我尝试在网站上使用它时它只是不起作用。
答案 0 :(得分:1)
当你这样写:
$("#"+pages[j]).animate({width: width}, "slow");
你没有输出任何东西,你正在执行它。如果你需要动态生成的javascript,我建议使用服务器端代码动态生成它。
但另一个,也许是最好的选择,就是让你的javascript更全面,因为它是非常多余的......
答案 1 :(得分:-1)
var wide = "700px";
var flat = "5px";
var pages = ["home","links","aktuell","kontakt"];
var selectors = [];
for(var i in pages) {
selectors.push('.' + pages[i]);
selectors.push('#' + pages[i]);
}
$(selectors.join()).bind("click", function() {
for(var j=0;j<pages.length;j++) {
var width;
if(pages[j] != pages[i])
width = flat;
else
width = wide;
$("#"+pages[j]).animate({width: width}, "slow");
}
});