简体   繁体   English

在页面加载时运行多个javascript函数

[英]run more than one javascript function on page load

  1. I want run some javascript functions on page load, which ways are exist and which one is better ? 我想在页面加载时运行一些javascript函数,哪些方法存在哪一个更好?
  2. can i call more than one function in <body onclick="my function();"> ? 我可以在<body onclick="my function();">调用多个函数吗?

First, you do not want to force the user to click on the page in order for the functions to execute. 首先,您不希望强制用户单击页面以执行功能。

The most basic way to do is: 最基本的方法是:

<body onload="yourFunction();">

Then, in a <script> tag in the <head> have your function call all your other functions: 然后,在<head><script>标记中,让您的函数调用所有其他函数:

function yourFunction(){
    function1();
    function2();
    // some other code not in a function...
    //...
}
<body onload="yourFunction1();yourFunction2();">

If you want to add different listeners, you'll need to use javascript. 如果要添加不同的侦听器,则需要使用javascript。 Check the answer to this question (edit: ok "need" is a bit strong, you can still do it directly in the tag :)) 检查这个问题的答案(编辑:确定“需要”有点强,你仍然可以直接在标签:) :)

Executing code on page load is not a trivial task because of cross-browser compatibility. 由于跨浏览器兼容性,在页面加载上执行代码不是一项简单的任务。 It is better to use one of the frameworks. 最好使用其中一个框架。 For example, jQuery: 例如,jQuery:

$(function () { /* your code */ });

As for binding several event functions to element - you can do it with jquery too: 至于将几个事件函数绑定到元素 - 您也可以使用jquery:

$('#mybytton').click(function () { /* first handler */ });
$('#mybytton').click(function () { /* second handler */ });

or 要么

$('#mybytton').click(function () { /* first handler */ })
    .click(function () { /* second handler */ });

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

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