简体   繁体   English

如何在不单击任何按钮的情况下调用HTML中的JavaScript函数?

[英]How to call JavaScript function in HTML without clicking any button?

My function is a timer that should run when the page is displayed. 我的功能是一个计时器,该计时器应在显示页面时运行。 I wrote 我写

<script>
    startcountdown();
</script>

In html but this doesn't work. 在html中,但这不起作用。 How can I call that function? 如何调用该函数? I don't need special event to happen before calling it. 调用之前,我不需要发生特殊事件。

<script>
window.onload = function() {
   startcountdown();
}
</script> 

You may use JavaScripts native window.onload function, if you are not using any other library like jQuery or something else. 如果未使用jQuery之类的任何其他库,则可以使用JavaScript的native window.onload函数。

<script>
  window.onload = function() {
    startcountdown();
  };
</script>

I'd also like to mention that you could also start a function by just adding it to the end of your markup. 我还要提及的是,您也可以通过将其添加到标记的末尾来启动函数。 That being said, if you define a function function startcountdown() { } at the very beginning of your html, you could simply use startcountdown(); 话虽如此,如果您在html的开头定义了函数function startcountdown() { } ,则可以简单地使用startcountdown(); at the very end of your html (eg before your closing </body> tag). 在html的最后(例如,在结束</body>标记之前)。

This approach would simply execute your function after your DOM has being loaded, since it's defined as the last call of your markup. 这种方法将您的DOM加载简单地执行您的函数,因为它被定义为标记的最后一次调用。

you can put it into tag using 'onload' event: 您可以使用“ onload”事件将其放入标签中:

or just use jQuery: 或者只是使用jQuery:

$(document).ready(function() {
    yourFunct();
});

you can try this put onload="startcountdown();" 您可以尝试一下put onload="startcountdown();" in html body tag 在html正文标签中

By calling your function in page on-load 通过在页面加载中调用函数

<script>
window.onload = startcountdown;
 function startcountdown(){
   //write your code here
}
</script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM