繁体   English   中英

车身负载 function in JavaScript

[英]Body onload function in JavaScript

我有我在我的网页下面发布的代码。 如您所见,它使用主体 onload function 来启动脚本。 有没有办法让这个脚本在没有这个和 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>

在此先感谢,卡勒姆

这可能是您要查找的内容: Attach a body onload event with JS

我建议使用 jQuery 或其他一些 JavaScript 框架,除非您正在探索 JS 或对使用库和框架有一些严格的限制。

the following code helpful for you
this is jquery:

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

or

$(window).load(function(){
function name();
});
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

如果您正在谈论通过在 html 中写入任何 javascript 来捕获 onload 事件,则可以使用此 function:

// 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;
        }
};

现在您可以在 onload 事件中运行所需的所有功能。

addEvent(window,'load',function () {
   box('query').focus();
   // or
   document.getElementById('query').focus();
});

暂无
暂无

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

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