Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - Document.write function replaces the whole page with the text

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...