[英]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.