[英]I am unable to loop and create multiple events
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
}
我不知道该怎么称呼,但是我想要的是在一周的每一天都具有此更改功能。
我的串联有问题吗? 循环肯定有效,我正在从数组中获取值。
当您在Javascript的循环内使用函数并且该函数使用loop变量时,它将捕获变量本身 ,而不是当前值。 因此,在循环结束时,变量是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
}
您会丢失i
的正确值,因为它不在for
循环中。
您可以改用$.each()
来创建一个闭包:
$.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
。 它快得多。
您也可以使用.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
});
变量在JavaScript中不是基于块范围的,因此传递给change()方法的函数将具有相同的i
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.