简体   繁体   中英

Function is not defined - Uncaught ReferenceError

I have this "Uncaught ReferenceError: function is not defined" error which do not understand.

If I have

$(document).ready(function() {
  function codeAddress() {
    var address = document.getElementById("formatedAddress").value;
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    });
  }
});

and

<input type="image" src="btn.png" alt="" onclick="codeAddress()" />
<input type="text" name="formatedAddress" id="formatedAddress" value="" />

When I press the button it will return the "Uncaught ReferenceError".

But if I put the codeAddress() outside the $(document).ready(function(){}) then it working fine .

My intention is put the codeAddress() within the document.ready function.

The problem is that codeAddress() doesn't have enough scope to be callable from the button. You must declare it outside the callback to ready() :

function codeAddress() {
    var address = document.getElementById("formatedAddress").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
        }
    });
}


$(document).ready(function(){
    // Do stuff here, including _calling_ codeAddress(), but not _defining_ it!
});

How about removing the onclick attribute and adding an ID:

<input type="image" src="btn.png" alt="" id="img-clck" />

And your script:

$(document).ready(function(){
    function codeAddress() {
        var address = document.getElementById("formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
            }
        });
    }
    $("#img-clck").click(codeAddress);
});

This way if you need to change the function name or whatever no need to touch the html.

Your issue here is that you're not understanding the scope that you're setting.

You are passing the ready function a function itself. Within this function, you're creating another function called codeAddress . This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).

For example:

var myfunction = function(){
    var myVar = 12345;
};

console.log(myVar); // 'undefined' - since it is within 
                    // the scope of the function only.

Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress method available to all:

$(function(){
    $("#imgid").click(function(){
        var address = $("#formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
           }
        });
    });  
});

(You should remove the existing onclick and add an ID to the image element that you want to handle)

Note that I've replaced $(document).ready() with its shortcut of just $() ( http://api.jquery.com/ready/ ). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById with the jQuery object.

You must write that function body outside the ready();

because ready is used to call a function or to bind a function with binding id like this.

$(document).ready(function() {
    $("Some id/class name").click(function(){
        alert("i'm in");
    });
});

but you can't do this if you are calling "showAmount" function onchange/onclick event

$(document).ready(function() {
    function showAmount(value){
        alert(value);
    }

});

You have to write "showAmount" outside the ready();

function showAmount(value){
    alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
    alert("will display on page load")
});

One more thing. In my experience this error occurred because there was another error previous to the Function is not defined - uncaught referenceerror .

So, look through the console to see if a previous error exists and if so, correct any that exist. You might be lucky in that they were the problem.

Clearing Cache solved the issue for me or you can open it in another browser

index.js

function myFun() {
    $('h2').html("H999999");
}

index.jsp

<html>
<head>
    <title>Reader</title>
</head>
<body>
<h2>${message}</h2>
<button id="hi" onclick="myFun();" type="submit">Hi</button>
</body>
</html>

please add the function outside the.ready function.

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

function listcoming() {}

Like this... it doesn't have enough space and scope inside the.ready f

Please check whether you have provided js references correctly. JQuery files first and then your custom files. Since you are using '$' in your js methods.

Thought I would mention this because it took a while for me to fix this issue and I couldn't find the answer anywhere on SO. The code I was working on worked for a co-worker but not for me (I was getting this same error). It worked for me in Chrome, but not in Edge.

I was able to get it working by clearing the cache in Edge.

This may not be the answer to this specific question, but I thought I would mention it in case it saves someone else a little time.

Sometimes it happens because of cache and cookies and the function that we created on the js file could not be loaded by the browser. So try to clear cache and cookies or press CTRL+F5 on the same page. Also, You can try to open it on incognito.

Just move the function to external js file as it is including $ code This error will be resolved

If you put the function between () it is a local function, so the function is only for that script.

 (function (){ // Local Function });

So if you delete the brackets, you will get a document function.

 (function (){ // Document Function });

And then you will be able to use the function in every script

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