I'm learning javascript and i want to experiment with innerHTML. I see that the random number appear briefly, but it doesn't 'stick' i.e. it disappears immendiately.
<script language="javascript" type="te开发者_如何学编程xt/javascript">
function getNbr(){
var n = Math.floor(Math.random() * 10) ;
document.getElementById("nbr").innerHTML = n ;
}
HTML:
<td id="nbr" width="75%"> </td> ...
<p><a href="javascript.html" onclick="getNbr()">get a number</a></p>
looking at below tutorial it seems very straightforward so i'm surprised it won't work for me
http://www.tizag.com/javascriptT/javascript-innerHTML.php
The hyperlink is redirecting. This causes the innerHTML to set, then the page is reloaded back to it's original state. If you are developing on a local machine this can be so quick you might conclude it's the Javascript. (Upload it to a webserver and you should see the page reloading a lot clearer).
Try changing the code to:
<p><a href="#" onclick="getNbr();return false;">get a number</a></p>
The hyper link doesn't need to be set, because you don't want it to redirect when you click it, so set it to #
.
The semi colons (;
) in the onclick
separate the code to be called. So you can have a big list of function calls for example:
"getNbr();anotherFunc();yetAnother();return false;"
The return false will stop any redirects or jumps after the functions have run (# href's default to the top of the page which is annoying if you have a long page).
It disappears because the document is redirected to the link href
. It got nothing to do with innerHTML.
To prevent it, add return false
like this:
onclick="getNbr(); return false;"
Your link is redirecting you to "javascript.html". So the results of your call are lost because the new page loads
The problem is here:
<p><a href="javascript.html" onclick="getNbr()">get a number</a></p>
When you click this anchor, you will be redirected to javascript.html page. You can use the following approach:
<p><a href="#" onclick="getNbr()">get a number</a></p>
精彩评论