简体   繁体   中英

Javascript functions not working in external .js file

I was using an external .js file for my JavaScript but I have encountered a problem with my HTML not being able to find any of my JavaScript functions. I know the functions work because if I move it from the external file to my html file it works fine. The error I get in the JavaScript console on Chrome is that my functions are not defined. I also know that my path to my external page works because I have some canvas tags that are reading the JavaScript perfectly fine.

To recap, this works:

HTML:

<canvas id="Canvas7"></canvas>

JavaScript:

window.onload = function() {
    var g=document.getElementById("Canvas7");
    var ctx=g.getContext("2d");
    var grd=ctx.createRadialGradient(75,50,5,90,60,100);
    grd.addColorStop(0,"red");
    grd.addColorStop(1,"white");
    ctx.fillStyle=grd;
    ctx.fillRect(10,10,150,80);

    // ...
};

But the following gives me the error "Uncaught ReferenceError: getLocation is not defined":

HTML:

<button onclick="getLocation()">Click here</button>

JavaScript:

window.onload = function() {
    var x=document.getElementById("location");
    function getLocation(){
        if (navigator.getlocation){
            navigator.getlocation.getCurrentPosition(showPosition,showError);
        }
        else{
            x.innerHTML="GeoLocation is not supported by this browser.";
        }
    }
    // ...
}

It's not a huge issue since I can just keep the JavaScript in my HTML file but it takes up a lot of space and I would prefer to keep everything organized. If anyone knows how I could solve this issue it would be much appreciated.

As you have defined your function(s) within the window.onload callback, getLocation is not a global function, so it is not known to the code provided to the onclick attribute. This is why your browser returned undefined . The easy fix is to make it a global function instead. For example:

window.getLocation = function() { ... }

However, requiring variables and functions to be defined globally is something you'll want to avoid long term on larger projects.

You can achieve this, by abandoning the use of HTML onclick attributes, and bind (non-global) callbacks from within your main code:

HTML:

<button id="getloc">Click here</button>

JavaScript:

document.addEventListener("DOMContentLoaded", function() {
    var x = document.getElementById("location");

    getloc.addEventListener("click", function() {
        if (navigator.getlocation){
            navigator.getlocation.getCurrentPosition(showPosition,showError);
        }
        else{
            x.textContent = "GeoLocation is not supported by this browser.";
        }
    });
    // ...
}

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