Document.write函数用文本替换整个页面 [英] Document.write function replaces the whole page with the text
问题描述
我对javascript比较新,我创建了一个将两个数字相乘的函数,但是 document.write
将整个页面替换为答案。我知道这是 document.write
应该做的,但只是想要一个替代。请记住,我对这门语言很陌生,所以如果可能的话,试着解释答案。谢谢!
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>
推荐答案
您已经知道如何使用 document.getElementById()
来检索页面上的输入值。所以做类似的事情来更新一个包含答案的元素:
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/
Simle demo: http://jsfiddle.net/V5R5h/1/
这篇关于Document.write函数用文本替换整个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!