How to convert this onclick() function to onload() [duplicate]

我只是一个虾纸丫 提交于 2020-04-07 04:05:12

问题


Possible Duplicate:
How to make onclick automatically through onload function

So I have the following function which is being called when I click a button. Here is the code:

<a href="#" role="button" onClick="myFunction('parameter')">

How can I call this function as soon as page is loaded? I tried onLoad function but doesn't seem to work.


回答1:


There are multiple options for onload event.

In HTML

<body onload="myFunction('parameter')">

In Javascript

window.onload=function(){
myFunction('parameter');
};

In JQuery

$(document).ready(function(){
      myFunction('parameter');
});



回答2:


Put this anywhere on your page, preferably in the <head>

<script type="text/javascript">    
$(function() {
    myFunction('parameter');
});
</script>

See https://stackoverflow.com/a/7911809/584192 for more ways of doing it via jQuery.




回答3:


Have you tried this:

window.onload = function(){
    myFunction('parameter');
}

See more at: https://developer.mozilla.org/en-US/docs/DOM/window.onload




回答4:


You call in myFunction document.ready or just before closing of body tag.

Within document.ready

Live Demo

<script type="text/javascript">    
    $(document).ready(function(){
          myFunction('parameter');
    });
</script>

Before closing body tag

<script type="text/javascript">    

     myFunction('parameter');

</script>



回答5:


You can use the following code.

<script>
   onload = function(){
     myFunction('parameter');
   }
</script>


来源:https://stackoverflow.com/questions/14453145/how-to-convert-this-onclick-function-to-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!