سؤال

I feel like I'm probably making a fundamental mistake here. I'm hoping someone can help me.

function countdown() {

  x = 5;

  for (i = x; i > 0; i--) {
    document.getElementById('display').innerHTML = (i + " ");
  }

}

This is a very small, simple replication of the problem I'm having.

I have a long function. Within that function is a variable, in this case: X.

I want to insert something into an element(in this case: #display) X amount of times.

I figured the best way to do this would be with a for loop, counting down from X by 1 and each time inserting the string I want.

But when it runs, it only returns 1. (I would expect it to return "5 4 3 2 1" in this case).

Please can someone explain to me why this doesn't work? I've been racking my brain over it for hours.

هل كانت مفيدة؟

المحلول

Because you are overwriting the content of the element in each iteration, by assigning a new value to innerHTML. You'd have to append instead:

document.getElementById('display').innerHTML += (i + " ");
//                                           ^

which is the same as

document.getElementById('display').innerHTML = 
    document.getElementById('display').innerHTML + (i + " ");

And of course it would be much better if you just built the string in the loop and set the content after the loop:

var content = '';

for (i = x; i > 0; i--) {
  content += (i + " ");
}

document.getElementById('display').innerHTML = content;

This way you avoid searching for the element in the document on every iteration. But .innerHTML is only useful to some degree, you should also have a look at DOM manipulation functions (such as .appendChild), once you are starting to do more evolved manipulations.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top