最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript doesn't execute on window.load - Stack Overflow

programmeradmin2浏览0评论

I have a javascript that executes within a element like : <a href="javascript:doSomething();"> but it doesn't execute on window.load , anyone knows why does that happen ?

I have a javascript that executes within a element like : <a href="javascript:doSomething();"> but it doesn't execute on window.load , anyone knows why does that happen ?

Share Improve this question asked Dec 29, 2009 at 14:08 Gandalf StormCrowGandalf StormCrow 26.2k71 gold badges179 silver badges268 bronze badges 2
  • because you didnt execute the javascript on window.load and used it on a.click instead maybe. – Numenor Commented Dec 29, 2009 at 14:22
  • did you mean window.onload instead of window.load? – Eran Medan Commented Dec 29, 2009 at 14:26
Add a ment  | 

4 Answers 4

Reset to default 6

With the example above doSomething() will only be called when the user clicks on the anchor. If you want it to execute on window.load you need to put the code in the head. i.e.

<script type="text/javascript">
    window.onload = doSomething;
</script>

Also, if you're going to be using the onload event a lot I would personally remend getting jQuery and using it's 'on DOM ready' event. This way your javascript will appear seamless to the end-user and won't have a flickering effect.

Have you tried writing <body onload="doSomething();">?

Assuming you did all the other suggestions, there is always a chance that someone later in the code (after your either <body onload=... or window.onload = ...) did exactly the same, and has overriden you.
If it happens to be the case (low chance) the solution to support both of your onload hooks, is window.attachEvent("onload", doSomething)

If I understand your problem correctly, you want to set an attribute in an element, calculating it dynamically via javascript, so that when the page is loaded your link points to the return value of "doSomething()".

For that you can use javascript's DOM manipulation utility functions. In your case something like:

<a id="myLink">my anchor</a>
...
<script type="text/javascript">
    getElementById('myLink').href = doSomething(); 
</script>
发布评论

评论列表(0)

  1. 暂无评论