for loop works fine with console.log but not innerHTML?

后端 未结 2 1075
南笙
南笙 2021-01-24 22:07

hello i\'m very new to javascript so forgive me if the answer seems obvious...

this is my code which is executed at the click of a button in the body

fun         


        
2条回答
  •  礼貌的吻别
    2021-01-24 22:54

    With innerHTML code inside the for loop you are always setting the value with the last time iterated value. Hence, you need to update your code to

     for ( var x = A; x < B; x = x + D ) {
    
        document.getElementById("q_box").innerHTML += x + "
    "; }

    OR

    var y = "";
     for ( var x = A; x < B; x = x + D ) {
    
         y += x + "
    "; } document.getElementById("q_box").innerHTML = y;

    I will recommend you to go for 2nd option, as it is better to set the updated value at once and not to extract the value and update for each iteration.

提交回复
热议问题