for(i=0;i<daysofweek.length;i++){
$("input[name=" + daysofweek[i] + "]").change(function(){ if($(this).is(':checked')){ $("#" + daysofweek[i] + "_content").show();}else{ $("#" + daysofweek[i] + "_content").hide(); } }) //loop through all days of the week creating the event that show/hides days
}
我不知道该怎么称呼它,但我想要的是在一周中的每一天都有这个改变功能。
我的连接有什么问题吗?循环肯定正在工作,我从数组中获取值。
答案 0 :(得分:2)
当您在Javascript中使用循环内的函数并且函数使用循环变量时,它会捕获变量本身,而不是当前值。所以在循环结束时,变量是i
到达的最后一个值。你需要将它全部包装在另一个函数中,并将变量的当前值传递给它。
for(i=0;i<daysofweek.length;i++){
(function(i) {
$("input[name=" + daysofweek[i] + "]").change(function() {
if($(this).is(':checked')) {
$("#" + daysofweek[i] + "_content").show();
} else {
$("#" + daysofweek[i] + "_content").hide();
}
});
})(i); //loop through all days of the week creating the event that show/hides days
}
答案 1 :(得分:2)
您丢失了i
的正确值,因为它不在for
循环中作用域。
你可以use $.each()
instead创建一个闭包:
$.each(daysofweek, function(i, val) {
$("input[name=" + daysofweek[i] + "]").change(function() {
if ( this.checked ) {
$("#" + daysofweek[i] + "_content").show();
} else {
$("#" + daysofweek[i] + "_content").hide();
}
}); //loop through all days of the week creating the event that show/hides days
});
另外,我将$(this).is(':checked')
更改为this.checked
。它要快得多。
您还可以简化by using .toggle()
而不是show/hide
。
$.each(daysofweek, function(i, val) {
$("input[name=" + daysofweek[i] + "]").change(function() {
$("#" + daysofweek[i] + "_content").toggle( this.checked );
}); //loop through all days of the week creating the event that show/hides days
});
答案 2 :(得分:1)
变量在JavaScript中不是块作用域的,因此传递给change()方法的函数都具有相同的i
值。