如何在页面加载时调用JavaScript函数? [英] How do I call a JavaScript function on page load?

查看:107
本文介绍了如何在页面加载时调用JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传统上,要在页面加载后调用JavaScript函数,您需要向包含一些JavaScript的主体添加 onload 属性(通常只调用一个函数) ):

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function):

<body onload="foo()">

当页面加载完毕后,我想运行一些JavaScript代码来动态填充页面的部分内容来自服务器的数据。我不能使用 onload 属性,因为我使用的是JSP片段,它没有 body 元素我可以添加属性为。

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

还有其他方法可以在加载时调用JavaScript函数吗?我宁愿不使用jQuery,因为我对它不是很熟悉。

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

推荐答案

如果你想要onload方法参数,你可以做类似的事情:

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

这将onload绑定到匿名函数,在调用时,将运行所需的函数,无论参数如何你给它。当然,您可以在匿名函数中运行多个函数。

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

这篇关于如何在页面加载时调用JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆