我正在尝试在 JavaScript/jQuery 中做一个简单的 for 循环 每次我单击“下一步”时,我希望 I 增加一次。
但是它不起作用。当我按下下一步时,什么也没有发生。
<script>
//function to show form
function show_form_field(product_field){
$(product_field).show("slow");
}
$(document).ready(function(){
//start increment with 0, until it is reach 5, and increment by 1
for (var i=0; i < 5 ;i++)
{
//when I click next field, run this function
$("#next_field").click(function(){
// fields are equial to field with id that are incrementing
var fields_box = '#field_'+[i];
show_form_field(fields_box)
})
}
});
</script>
最佳答案
您不需要 for 循环。只需在 click 函数外部声明 var i 并在函数内部递增它即可。
//function to show form
function show_form_field(product_field) {
$(product_field).show("slow");
}
$(document).ready(function () {
var i = 0; // declaring i
$("#next_field").click(function () {
if (i <= 5) { // Checking whether i has reached value 5
var fields_box = '#field_' + i;
show_form_field(fields_box);
i++; // incrementing value of i
}else{
return false; // do what you want if i has reached 5
}
});
});
关于javascript - 使用 jQuery 和 JavaScript 的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21153637/