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

萝らか妹 提交于 2019-12-02 05:09:22
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 +=

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!