简体   繁体   English

调用onload事件的功能不止是函数调用

[英]Calling onload event with more than function call

I have something like this in my html: 我的html中有类似的内容:

<body onload='myjavascriptfunction1()'

I also want to be able, with the same onload event to call 'myjavascriptfunction2() along with myjavascriptfunction1()'. 我还希望能够使用相同的onload事件来调用“ myjavascriptfunction2()和myjavascriptfunction1()”。 Please, is this possible? 拜托,这可能吗?

You can do it like this: 您可以这样做:

<body onload='myjavascriptfunction1();myjavascriptfunction2()'>

or create a function and then call from that function the other functions you want 或创建一个函数,然后从该函数调用所需的其他函数

function myjavascriptfunction1(){
    myjavascriptfunction2();
    myjavascriptfunction3();
}

You just need a semicolon: 您只需要一个分号:

<body onload='myjavascriptfunction1(); myjavascriptfunction2()'>

Also, you never actually added the > end of your body tag. 此外,您实际上从未添加body标签的>末尾。

Use a generic OnLoad function 使用通用的OnLoad函数

<body onload='onLoad()'>

function onLoad(){
    myJSFunction1();
    myJSFunction2();
}

But a better way would be to subscribe to the onload event using addEventListener 但是更好的方法是使用addEventListener订阅onload事件

window.addEventListener("load", myJSFunction1, false);
window.addEventListener("load", myJSFunction2, false);

JSFiddle 的jsfiddle

This keeps your JS separate from your HTML and prevents you from adding the ugly onLoad attribute to the body tag. 这使您的JS与HTML分开,并防止您将丑陋的onLoad属性添加到body标签。

Attach Event Listeners rather than defining onload events in the markup 附加事件侦听器,而不是在标记中定义onload事件

  document.body.addEventListener("load", do_something(), false);

  function do_something() {
    alert("hello universe");
    //do something here
  }

Refer to Event Listeners documentation for more info. 有关更多信息,请参考事件监听器文档。 If your event listener has to work on multiple browsers like legacy IE's you might have to define other event listeners like attachEvent . 如果事件侦听器必须在多个浏览器(如旧版IE)上运行,则可能必须定义其他事件侦听器(如attachEvent Libraries like jQuery are handy for these needs as you don't have to worry about browser compatibilities. 诸如jQuery之类的库可轻松满足这些需求,因为您不必担心浏览器的兼容性。

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

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