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

I have a javascript that executes within a element like : <a href="javascript:doSomething();&qu

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745469916a4629087.html

相关推荐

  • javascript doesn&#39;t execute on window.load - Stack Overflow

    I have a javascript that executes within a element like : <a href="javascript:doSomething();&qu

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信