Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么可以';我是否在document.onload中编写代码而不是放置函数?_Javascript - Fatal编程技术网

Javascript 为什么可以';我是否在document.onload中编写代码而不是放置函数?

Javascript 为什么可以';我是否在document.onload中编写代码而不是放置函数?,javascript,Javascript,我能够做到这一点: document.onload = init(); 但不是这个: document.onload = function() { alert('Test'); } 为什么 编辑: 这是init() 我需要在函数周围添加一些括号,然后在末尾添加另一对括号来调用它: document.onload = (function() { init(); })() 试试这个: document.onload = init(){ alert('Test'); } 重载

我能够做到这一点:

document.onload = init();
但不是这个:

document.onload = function() {
  alert('Test');
}
为什么

编辑:

这是init()


我需要在函数周围添加一些括号,然后在末尾添加另一对括号来调用它:

document.onload = (function() {
  init();
})()
试试这个:

document.onload = init(){ 
    alert('Test');
}

重载
init
函数,
document.onload
最初调用
init
函数。

document.onload=init()
只不过是调用
init
functin并将返回值赋给
document.onload
<代码>document.onload=init我认为第二个是可行的,而不是第一个。我在
init
中放置了一个
alert()
。当我执行
document.onload=init()时
弹出警报,但当我执行
document.onload=init时它没有。为什么?在这种情况下,您甚至不需要
document.onload=
。只要用生命
document.onload = init(){ 
    alert('Test');
}