JavaScript result does not appear on one page

function result() { var a, b, c; a = 10; b = 20; c = a+b; document.write("The result of a+b is" + c); } <input type="button" value="Result" onclick=result();> 

I am new to JavaScript and I am learning step by step. I tried the above example and it works fine, but after clicking the button, the result is not displayed in one window.

Should I use innerHTML? But how can I use, I do not know. And is using innerHTML useful for programming?

+4
source share
7 answers

document.write ALWAYS launches a new page, unless it loads. After the current page finishes loading, all document.write documents will be written to the NEXT web page, which will be displayed, not the current one, because it has already been written.

use DOM methods like this:

 <script type="text/javascript"> function result() { var a, b, c; a = 10; b = 20; c = a+b; document.getElementById('foo').innerHTML = "The result of a+b is" + c; return false } </script> <span id="foo"></span> <input type="button" value="Result" onclick="return result();"> 
+3
source

Any document.write () must be called before the page finishes loading, otherwise it will open a new page (see this link for help), it is possible that your problem

you can do something like

 function result() { var a, b, c; a = 10; b = 20; c = a+b; var content = document.getElementById('result_div').innerHTML; content += "The result is ..." ; } 
+1
source

If this is for debugging purposes, use console.log(value) , otherwise, yes, save the value in innerHTML .

 console.log("The result of a+b is" + c); alert("The result of a+b is" + c); // For very old browsers. 

using the innerHTML property:

 document.getElementById('{id}').innerHTML = "The result of a+b is" + c; 
0
source

Try this code

 function result() { var a, b, c; a = 10; b = 20; c = a+b; console.log("The result of a+b is" + c); } 
0
source

This will result in writing the result to a separate element without overwriting the entire document:

 <script type="text/javascript"> function result() { var a, b, c; a = 10; b = 20; c = a+b; var result = document.getElementById("result"); result.innerHTML = "The result of a+b is" + c; } </script> <input type="button" value="Result" onclick=result();><div id="result"></div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

see http://jsfiddle.net/AcTM2/

0
source

Change the result of the method:

 function result() { var a, b, c; a = 10; b = 20; c = a+b; document.getElementById('result').innerHTML="The result of a+b is" + c; } 

and then put the div with the id result in the body:

 <div id="result"></div> 
0
source

to try

 function result() { var a, b, c; a = 10; b = 20; c = a+b; var result = "The result of a+b is" + c; document.body.appendChild(document.createTextNode(result)); document.body.appendChild(document.createElement("br")); } 

This way you will not need to create an additional node to store the result data.

0
source

Source: https://habr.com/ru/post/1440741/


All Articles