Document.write function replaces the whole page wi

2019-01-20 17:31发布

问题:

I am relatively new to javascript and I created a function to multiply two numbers together, but document.write replaces the whole page with the answer. I know this is what document.write is supposed to do, but just wanted an alternative. Remember, I am new to the language, so if it's possible, try to explain the answer. Thanks!

<script language="javascript">
    function calculate(){
        var number1= document.getElementById("num1"); 
        var number2= document.getElementById("num2");
        var answer=number1.value * number2.value;
        document.write(answer);
    }
</script>

回答1:

You already know how to use document.getElementById() to retrieve the values of inputs on your page. So do something similar to update an element that holds the answer:

<div id="answer"></div>

...and then:

document.getElementById("answer").innerHTML = answer;

Simle demo: http://jsfiddle.net/V5R5h/1/



回答2:

If you add an empty element like <span id="fillme"></span> to the document you can use this with var fillme = document.getElementById("fillme"); and then later assign content to fillme with fillme.innerHTML = answer;