简体   繁体   中英

javascript: calling function in for-loop

loop that executes a function. However, the following works - the counter counts while the images on the page are loaded.

var progress = function()
 {
   for (var i = 0; i < slide.length; i++)
    slide[i].onload = function(){
         actualprogress +=1,
         loading.innerHTML = actualprogress
    };
 }

While the following does not work. When I open the Page the counter says "[n]" (number of slides, eg "12") from the beginning.

var progress = function()
 {
   var action = function(){
     actualprogress +=1;
     loading.innerHTML = actualprogress
   }
   for (var i = 0; i < slide.length; i++)
     slide[i].onload = action();
 }

I would like to call a function from the for-loop because I will need to do other and more things within the function. Why doesn't this work?

In the first code you are assigning the function pointer to the onload property.

In the second code you are assigning the function returned value to the onload property which is null .

There is a huge difference between those. The parantheses are extra in the second code, after action .

onload = action() => onload = action

Cheers

On the last line of the second snippet, you're calling the function, instead of just assigning it to slide[i].onload .

Simply change slide[i].onload = action(); to slide[i].onload = action; .

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