JS if statement - innerHTML

廉价感情. 提交于 2019-12-26 03:53:05

问题


function colorize(){
    for(i = 1; i<=8; i++)
    {
        var id = document.getElementById('op' + i);

        var stat = id.innerHTML;
        document.write(stat + " ");
        if(stat == 1)
        {
            id.innerHTML = "<div style='background:#00FF00; width: 20px; height: 20px; border-radius: 15px;'></div>";
        }
        else{
            id.innerHTML = "<div style='background:#FF0000; width: 20px; height: 20px; border-radius: 15px;'></div>";
        }
    }
}

It should check if there is a 1 or 0 and replace it with a green or red circle, but I only get red circles.

"stat" printing gave me an " 0 0 0 1 1 1 1 1" but it seem to be not working with the if statement. Does anybody know why?


回答1:


If stat.length always equals 1:

if(stat[0]=='1'){

If all you are looking for is a 1 in stat:

if(stat.match(/1/)){//contains a 1, may contain more



回答2:


function colorize(){
for(i = 1; i<=8; i++)
{
    var id = document.getElementById('op' + i);

    var stat = id.innerHTML;
    document.write(stat + " ");
    if(stat == "1")
    {
        id.innerHTML = "<div style='background:#00FF00; width: 20px; height: 20px; border-radius: 15px;'></div>";
    }
    else{
        id.innerHTML = "<div style='background:#FF0000; width: 20px; height: 20px; border-radius: 15px;'></div>";
    }
}

}



来源:https://stackoverflow.com/questions/16881302/js-if-statement-innerhtml

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