开发者

Function calling in javascript

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜