简体   繁体   中英

How to fix this error in javascript

I have high number of functions which are binding to different elements.

Hence, I decided to define all my functions in one file & then call from other file.

HTML

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/js/jquery.min.js"></script>
<script src="~/js/functions.js"></script>
<script src="~/js/site.js"></script>
</head>
<body>
<div>
    Hello!! This is a sample page
</div>
</body>
</html>

functions.js

$(document).ready(function (e) {
//like this I have 50+ functions 
function GetCustomers()
{

   //ajax call.
}

});

site.js

$(document).ready(function (e) {
 GetCustomers();
});

But this is throwing the below error.

错误

Uncaught ReferenceError: GetCustomers is not defined

$(document).ready(function (e) {
//like this I have 50+ functions 
function GetCustomers()
{

   //ajax call.
}

});

You define the function inside the ready handler, keeping it local to that scope. Move it outside (or just get rid of the $(document).ready() ) so that's it's in global scope. See function scoping docs.

If you don't want to add all of these functions to the global scope, you could create an global object, and add these as methods:

var app = {
    getCustomers: function(){},
    ...
};

从您的functions.js中删除包装的$(document).ready()

Do not use the function inside document ready.

$(document).ready(function (e) {

 function GetCustomers()
{

 //ajax call.
 }

});

Use like

<script>

function GetCustomers()
{

 //ajax call.
 }
</script>

There is no need to wrap all your functions in $(document).ready and that's your issue. Two-problems:

  1. .ready doesn't fire away so that code isn't executed (and therefore your functions aren't created)
  2. since you're doing it in .ready your not binding your functions to the window and so they can't be accessed anywhere else.

write your function out side the document.ready()

 <script>
   function GetCustomers()
   {
       //your code.
   }
 </script>

GetCustomers从document.ready函数中拉出。

如果要在单独的文件中定义,请勿在functions.js中的document.ready内部使用GetCustomers,而应直接定义函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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