[英]For loop using jQuery and JavaScript
I'm trying to do a simple for loop in JavaScript/jQuery every time I click NEXT, I want the I to increment once. 每次单击NEXT时,我都试图在JavaScript / jQuery中做一个简单的for循环,我希望I递增一次。
But it is not working. 但这是行不通的。 When I press next, nothing happens. 当我按下一步时,什么也没有发生。
<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>
You should declare variable i document wide, not inside the click handler. 您应该在整个文档中声明变量,而不是在单击处理程序中声明。
//function to show form
function show_form_field(product_field){
$(product_field).show("slow");
}
$(document).ready(function(){
var i=0;
$("#next_field").click(function(){
var fields_box = '#field_'+ i++ ;
show_form_field(fields_box)
})
});
You do not need the for loop. 您不需要for循环。 Just declare var i
outside click function and increment it inside the function. 只需在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
}
});
});
Call $("#next_field").click just one time, and in the click function, increase i every time. 调用$(“#next_field”)。单击一次,然后在click函数中,每次增加i。
$(document).ready(function() {
var i = 0;
$("#next_field").click(function() {
if (i >= 5) {
//the last one, no more next
return;
}
show_form_field('#field_' + (i++));
});
});
try this 尝试这个
$(document).ready(function(){
//start increment with 0, untill it is reach 5, and increment by 1
var i = 0;
$("#next_field").click(function(){
// fields are equial to field with id that are incrementing
if(i<5)
{
var fields_box = '#field_'+i;
show_form_field(fields_box);
i+=1;
}
else
{
return;
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.