InnerHTML Basics

I am learning javascript and I want to experiment with innerHTML. I see that a random number appears for a short time, but it does not “stick”, that is, it disappears very slowly.

<script language="javascript" type="text/javascript">
function getNbr(){
var n = Math.floor(Math.random() * 10) ;
document.getElementById("nbr").innerHTML = n ;
}

HTML:

<td id="nbr" width="75%">&nbsp;</td> ...
<p><a href="javascript.html" onclick="getNbr()">get a number</a></p>

looking below the tutorial seems very simple, so I am surprised that this will not work for me.

http://www.tizag.com/javascriptT/javascript-innerHTML.php

+3
source share
4 answers

The hyperlink is redirected. This causes innerHTML to be set, then the page reloads back to its original state. If you work on a local machine, it can be so fast that you can do this Javascript. (Upload it to the web server and you will see that reloading the page is much clearer).

Try changing the code to:

<p><a href="#" onclick="getNbr();return false;">get a number</a></p>

, , #.

(;) onclick , . , , :

"getNbr();anotherFunc();yetAnother();return false;"

false (# href , , ).

+4

, href. innerHTML.

, return false :

onclick="getNbr(); return false;"
+3

"javascript.html". , ,

+2

:

<p><a href="javascript.html" onclick="getNbr()">get a number</a></p>

, javascript.html. :

<p><a href="#" onclick="getNbr()">get a number</a></p>
+1

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


All Articles