【问题标题】:Recursive loop in javascript with increment based on a link clickjavascript中的递归循环,基于链接点击的增量
【发布时间】:2013-08-28 18:21:07
【问题描述】:

我正在填充表单字段并使用 javascript 递归循环通过它们提示用户。

我遇到了递归无法按预期工作的问题。

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

field1 和 field2 按预期填充,但 field3 和 field4 一起触发,field5 和 field6 一起触发。

我认为这与全局变量与局部变量有关,或者可能与 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);
}

【问题讨论】:

    标签: javascript jquery recursion


    【解决方案1】:

    试试这个:

    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/

    希望对你有帮助。

    【讨论】:

    • 谢谢!这很有帮助。看起来您刚刚添加了 e.preventDefault();关于点击功能。
    • 我刚刚调整了填充字段值的位置,用户需要选择数据然后单击链接来填充字段。 jsfiddle.net/9QtDw/7感谢您的帮助。
    【解决方案2】:

    你没有循环!!! 你只是循环2次 你应该像这样改变你的循环功能:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-22
      • 2014-08-23
      • 1970-01-01
      • 2012-05-25
      • 2018-10-24
      • 2020-03-10
      • 1970-01-01
      • 2013-09-30
      相关资源
      最近更新 更多