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

别说谁变了你拦得住时间么 提交于 2019-12-20 05:15:19

问题


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

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 />";

    }


}

i'm pretty sure the error is in the for loop... the output is supposed to be a list of numbers between A and B. and changing the innerHTML = to innerHTML += hasn't worked either?


回答1:


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 +=




回答2:


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.



来源:https://stackoverflow.com/questions/34319325/for-loop-works-fine-with-console-log-but-not-innerhtml

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