Something weird happens that I can't explain! When i call a function from the javascript for example:
<script type='text/javascript'>
callFunction()
</script>
The function is called but it produces an error for non declared variable.
When i call the same function through a link i.e. :
<a href="#" onclick="callFunction(); return false;"> L开发者_如何学JAVAink </a>
The function runs succesfully and produces the correct output!
Any ideas why this happens?
most likely you try to call the function before it became declared - make sure that this isn't the case and that the function isn't declared somewhere below the block where you try to call it.
By the time, the first script is executed, there is no function callFunction
yet. When you click the link however, the page has already loaded far enough so that the function is available.
The solution is to wait for the page to load, before you call functions. Nearly all JavaScript frameworks (JQuery, MooTools etc.) offer an event handler, that is called when the DOM, that is the underlying structure of the document, is ready. If you don't want to use a framework, you can also wait for the document to load (i.e. the load event), but that is usually called later than domready.
精彩评论