如何使用innerHTML显示多个输出?

时间:2013-12-16 09:45:58

标签: javascript

我在脚本中有这个功能。

function arith()
{
    var n1 = parseInt(document.getElementById('num1').value, 10);
    var n2 = parseInt(document.getElementById('num2').value, 10);
    var newVal;
    if(op == "Operation 1")
    {
        newVal1 = n1 + n2;
    }
    else if(op == "Operation 2")
    {
        newVal2 = n1 - n2;
    }
    else if(op == "Operation 3")
    {
        newVal3 = n1 * n2;
    }
    else if(op == "Operation 4")
    {
        newVal4 = n1 / n2;
    }

    var demoP = document.getElementById("demo");
    {
        demoP.innerHTML = "Operation 1=" + newVal1;
        demoP.innerHTML = "Operation 2=" + newVal2;
        demoP.innerHTML = "Operation 3=" + newVal3;
        demoP.innerHTML = "Operation 4=" + newVal4;
    }

    return false;
}

当我调用这些innerHTML时,我可以使用<p id="demo"></p> 是否足够或者我需要调用每个元素?

5 个答案:

答案 0 :(得分:3)

innerHtml的调用将覆盖每次调用的内容。在分配到String属性之前,在innerHTML中构建HTML。

var demoP = document.getElementById("demo");
{
                    var html = "";
                    html += "Operation 1=" + newVal1 + "<br/>";
                    html += "Operation 2=" + newVal2 + "<br/>";
                    html += "Operation 3=" + newVal3 + "<br/>";
                    html += "Operation 4=" + newVal4 + "<br/>";
                    demoP.innerHTML = html;
}

JS小提琴: http://jsfiddle.net/D3xR3/

答案 1 :(得分:2)

您应该使用+=代替=,否则会覆盖您的数据。

demoP.innerHTML += "Operation 2=" + newVal2;

调用一次就足够了。

答案 2 :(得分:1)

您当前的代码首先将元素的.innerHTML设置为"Operation 1=" + newVal1,然后使用其他值将其覆盖三次。也许您打算将所有结果连接在一起并将结果放在该元素中:

demoP.innerHTML = "Operation 1=" + newVal1 + "<br>"
                + "Operation 2=" + newVal2 + "<br>"
                + "Operation 3=" + newVal3 + "<br>"
                + "Operation 4=" + newVal4;

答案 3 :(得分:0)

最好的恕我直言将连续字符串和最新时刻添加到DOM(节省时间)

var html = "Operation 1=" + newVal1;
html += "Operation 2=" + newVal2;
html += "Operation 3=" + newVal3;
html += "Operation 4=" + newVal4;

var demoP = document.getElementById("demo");
demoP.innerHTML = html;

此外,demop之后的括号是不必要的

答案 4 :(得分:0)

你在一行中完成:

demoP.innerHTML = "Operation 1=" + newVal1 + "<br>"+ "Operation 2=" + newVal2 + "<br>"+ "Operation 3=" + newVal3 + "<br>"+"Operation 4=" + newVal4;