Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.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
加载html页面时从外部文件调用Javascript函数_Javascript_Jquery_Html - Fatal编程技术网

加载html页面时从外部文件调用Javascript函数

加载html页面时从外部文件调用Javascript函数,javascript,jquery,html,Javascript,Jquery,Html,我想从名为hello.js的Javascript文件加载名为james()的函数,该文件作为外部文件添加到index.html 我的问题是,当函数james在$(document).ready(function())中声明时,它只是说“james function未定义”,没有调用。如何使用onload调用document.ready中声明的函数 <html> <head> </head> <body onload= "james()">

我想从名为
hello.js
的Javascript文件加载名为
james()
的函数,该文件作为外部文件添加到
index.html

我的问题是,当函数james在
$(document).ready(function())
中声明时,它只是说“james function未定义”,没有调用。如何使用onload调用document.ready中声明的函数

<html>
<head>
</head>
<body onload= "james()">
         <script src=hello.js>
</body>
</html>
您的“james”函数不在正确的范围内。它在“就绪”事件侦听器中声明,并且仅存在于侦听器范围内。之后,它将不再可用

你不能做你想做的事。函数不能在声明它们的作用域之外使用。 将函数移到全局范围

function mountApp{

   $(document).ready(function(){
     // You can call the function from here
     james();
   });
}

function james(){
  alert("how can i get call ,when html page is loaded");
}

现在,我不明白为什么要在函数中添加事件监听器“onready”,因为函数调用只会在DOM就绪后执行,所以它永远不会触发。

真正的方法是,在document.ready函数之外创建函数,然后调用

function james()
{
  alert("how can i get call ,when html page is loaded");
}
$(document).ready(function(){
 james();
)};

您好@bbmac,我认为您需要在
hello.js
脚本之前将jquery添加到您的HTML中,因为
ready
是一个jquery函数问题是因为从*属性上调用的函数需要在全局范围内。部分是因为这个原因,他们应该被避免。只需从
document.ready()
(或
$(窗口)中调用
james()
。直接在('load')
)处理程序上执行。“函数调用将仅在DOM准备就绪后执行”-作为一般语句,这是不正确的。函数调用将在任何时候执行。在这种特殊情况下,函数调用是在加载事件处理程序中完成的,因此该调用将一直等到DOM就绪之后。
function james()
{
  alert("how can i get call ,when html page is loaded");
}
$(document).ready(function(){
 james();
)};