简体   繁体   中英

Recursive Javascript function using callback not working

I am trying to fix a problem with my recursive function JS using a call back. I just want to update the HTML of 3 div using according to an index. Please find the code below

<div id="try0">50</div>
<div id="try1">50</div>
<div id="try2">50</div>

function getNumberOfAnswers(questionID, callback)
{
  var value = i*10;
   callback( value.toString());

}

var i=0;
getNumberOfAnswers(i, function callFunc(ratio){
    var itemToChg = 'try'+i;
document.getElementById(itemToChg).innerHTML = ratio;
    if(i<3){
        i++;
        getNumberOfAnswers(i,callFunc(ratio));

    }

    });

I didn't put any tags on the code above to simplify but I made a JSfiddle with it. http://jsfiddle.net/cyrilGa/zmtQ8/ . On the third line from the end, I tried to write getNumberOfAnswers(i,ratio); but it didn't work. Can somebody help me with this Cheers

The line:

var value = i*10; 

should be

var value = questionID * 10;

And I think

getNumberOfAnswers(i,callFunc(i));

Should be:

getNumberOfAnswers(i,callFunc);

Do not use recursion for this, it is silly.

for ( var i = 0; i < 3; i++ ) {
    document.getElementById('try' + i).innerHTML = i * 10;
}

Is this what you want?

You need to replace the recursive callFunc(ratio); at the bottom to callFunc(i); because the argument ratio is still equal to 0 while you increment i . Everything else is fine.

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