简体   繁体   中英

Recursive loop in javascript with increment based on a link click

I'm populating form fields and prompting the user through them using a javascript recursive loop.

I'm having a problem with the recursion not working as expected.

I have a recursive loop that prompts a user through 6 input fields.

field1 and field2 populate as expected, but field3 and field4 fire off together and field5 and field6 fire off together.

I think it has something to do with global vs. local variables or possibly scoping inside the loop() function, but I'm struggling with figuring it out.

JSFiddle: http://jsfiddle.net/9QtDw/5/

Click on the "Save Data" button to fire off the loop and you can see the loop() function iterate with confirm popups guiding the user.

Any help pointing me in the right direction is greatly appreciated.

var x = 0;

var fieldnames = ["field1", "field2", "field3", "field4", "field5", "field6"]

function loop(y) {
i = y;
if (i >= fieldnames.length) { // check to see if loop has run through the number of elements in  the fieldnames array
    return;
}
confirm( 'Highlight the ' + fieldnames[i] + ' text' );
console.log("outside on click function i=" + i);

//function to be called when button is clicked
$("#text-submit").on("click", function(){
    //fieldinfo = $("#cs-ResultText").text();
    $('#' + fieldnames[i] + '').val('this is where i = ' + i);

    // increment i and recall the loop function for the next field
    if(i >= fieldnames.length - 1 ){ return false; }

    i=i+1; 
    console.log(i);

    console.log("inside on click function i=" + i);
    return loop(i); // the recusive call back into the loop
});
return false;
}

// only fire off the loop call on the first run through, after that it's called on #text-submit click
if( x === 0 ){
loop(x);
}

You are not looping!!! ya just loop for 2 time you should change your loop function like this:

function loop(y) {
i = y;
if (i >= fieldnames.length) { // check to see if loop has run through the number of elements in  the fieldnames array
    return;
else
$("#text-submit").trigger('click')
}

try this instead:

var x = 0;

var fieldnames = ["field1", "field2", "field3", "field4", "field5", "field6"]

function loop(y) {
    i = y;
    if (i >= fieldnames.length) { return; }
    confirm( 'Highlight the ' + fieldnames[i] + ' text' );  
    $('#' + fieldnames[i] + '').val('this is where i = ' + i);
    return false;
}

$("#text-submit").on("click", function(e){        
    e.preventDefault();            
    if(i >= fieldnames.length - 1 ){ return false; }        
    i=i+1;               
    loop(i);
});

if( x === 0 ){
    loop(x);
}

working fiddle here: http://jsfiddle.net/9QtDw/6/

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM