JavaScript 中的主体加载函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5851408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Body onload function in JavaScript
提问by Callum Whyte
I have the code that I have posted below in my webpage. As you can see it uses the body onloadfunction to launch the script. Is there any way of making this script work without this and in JavaScript instead?
我有我在我的网页下面发布的代码。如您所见,它使用主体 onload函数来启动脚本。有没有办法让这个脚本在没有这个的情况下工作,而是在 JavaScript 中工作?
<!doctype html>
<html>
<head>
<script type="text/javascript">
function box(query){
return document.getElementById(query)
}
</script>
</head>
<body onload="box('query').focus();">
<input id="query" type="text">
</body>
</html>
Thanks in advance, Callum
提前致谢,卡勒姆
回答by no.good.at.coding
This might what you're looking for: Attach a body onload event with JS
这可能是您正在寻找的:使用 JS 附加一个主体 onload 事件
I'd suggest using jQuery or some other JavaScript framework unless you're exploring JS or have some stringent restrictions on using libraries and frameworks.
我建议使用 jQuery 或其他一些 JavaScript 框架,除非您正在探索 JS 或对使用库和框架有一些严格的限制。
回答by no.good.at.coding
the following code helpful for you
this is jquery:
$(document).ready(function(){
function name();
});
or
$(window).load(function(){
function name();
});
回答by no.good.at.coding
the following answers using javascript:
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function load() {
alert('function loaded');
}
window.onload = load;
</script>
</head>
<body>
</body>
</html
----------
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function load() {
alert('function loaded');
}
</script>
</head>
<body onload="load();">
</body>
</html
回答by Ibu
if you are talking about catching the onload event with writting any javascript in your html you can use this function:
如果您正在谈论通过在您的 html 中编写任何 javascript 来捕获 onload 事件,您可以使用此功能:
// Add event
var addEvent = function (obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
}else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
};
Now you can run all the functions you need in your onload event.
现在您可以在 onload 事件中运行您需要的所有功能。
addEvent(window,'load',function () {
box('query').focus();
// or
document.getElementById('query').focus();
});