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

后端 未结 2 1067
南笙
南笙 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:47
    function q() { 
    
        var A = +document.getElementById("time_one").value;
        var B = +document.getElementById("time_two").value;
        var C = +document.getElementById("post_number").value;
    
        var D = (B - A) / C;
    
        for ( var x = A; x < B; x = x + D ) {
    
        document.getElementById("q_box").innerHTML += x + "<br />";
    
        }
    
    }
    

    You should convert the values in int and you should use +=

    0 讨论(0)
  • 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 + "<br />";
    
        }
    

    OR

    var y = "";
     for ( var x = A; x < B; x = x + D ) {
    
         y += x + "<br />";
    
        }
    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.

    0 讨论(0)
提交回复
热议问题