2014-01-16 78 views
0

我試圖做一個簡單的循環在JavaScript/jQuery 每次我點擊NEXT,我希望我增加一次。For循環使用jQuery和JavaScript

但它不工作。當我按下時,沒有任何反應。

<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> 
+0

不把這個循環中,使用「這個」 ......對於 – softsdev

+1

$(「#next_field」)。單擊循環意味着綁定點擊功能的5倍.. – Andrew

+0

請出示你的HTML或創建一些小提琴演示 – softsdev

回答

2

你不需要在for循環。只需聲明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 
     } 

    }); 

}); 
0

調用$(「#next_field」),點擊一次,在點擊函數中,每次增加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++)); 
    }); 

}); 
2

你應該聲明變量i文檔範圍內,而不是在點擊處理程序中。

//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) 

     }) 

}); 
+1

其實你所做的是正確的..我不知道downvote .. +1 –

0

試試這個

$(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; 
      } 

     }); 

});