javascript中的递归循环,基于链接单击的增量

Recursive loop in javascript with increment based on a link click

本文关键字:链接 单击 于链接 递归 循环 javascript      更新时间:2023-09-26

我正在填充表单字段,并使用javascript递归循环提示用户完成这些字段。

我遇到了一个问题,递归没有按预期工作。

我有一个递归循环,提示用户通过6个输入字段。

场1和场2按预期填充,但场3和场4一起开火,场5和场6一起开火。

我认为这与全局变量与局部变量有关,或者可能与loop()函数内部的作用域有关,但我很难弄清楚。

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

点击"保存数据"按钮启动循环,您可以看到loop()函数迭代,并弹出确认弹出窗口指导用户。

非常感谢为我指明正确方向的任何帮助。

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);
}

请尝试以下操作:

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);
}

工作小提琴在这里:http://jsfiddle.net/9QtDw/6/

我希望它能有所帮助。

您没有循环!!!你只循环了两次你应该这样改变你的循环函数:

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')
}