简体   繁体   中英

Can't Find Cause and Solution to Javascript Error

When I run my code, there's an error saying: Cannot set property 'src' of null

The error is in this for loop:

for (i=1; i<=48; i++) {
    document.getElementById("hour" + i*6 + "map").src = mapAddresses[i-1];
}//end for

Here is all of the code leading up to that point:

<script>

    //Create Canvases and Images
    var canvas;
    var img;
    var index;

    for (var i = 1; i <= 40; i++) {
        index = 6 * i;
        canvas = document.createElement("canvas");
        canvas.id = "hour" + index + "canvas";
        canvas.width = 1024;
        canvas.height = 764;
        img = document.createElement("img");
        img.id = "hour" + index + "map";
        img.src = " ";
        canvas.appendChild(img);
        document.body.appendChild(canvas);
    }//end for

    //Time Variables
    var currentYear = new Date().getFullYear();
    var currentMonth = new Date().getMonth() + 1;
    var currentDay = new Date().getDate();
    var currentHour = new Date().getHours();
    var currentRun;

    //Formatting Time Variables for URLs
    if (currentMonth < 10) {
        currentMonth = "0" + currentMonth;
    }//end if
    if (currentDay < 10) {
        currentDay = "0" + currentDay;
    }//end if

    //Finding Latest Model Run      
    if (currentHour >= 0 && currentHour < 6) {
        currentRun = "00";
    }//end if
    if (currentHour >= 6 && currentHour < 12) {
        currentRun = "06";
    }//end if
    if (currentHour >= 12 && currentHour < 18) {
        currentRun = "12";
    }//end if
    if (currentHour >= 18 && currentHour < 24) {
        currentRun = "18";
    }//end if

    var currentRun = currentRun;

    //Creating URLs
    var mapAddresses = [];

    for (i=6; i<=240; i=i+6) {
    mapAddressFor = "http://www.tropicaltidbits.com/analysis/models/gfs/" + currentYear + currentMonth + currentDay + currentRun + "/gfs_mslp_pcpn_neus_" + i/6 + ".png";
    mapAddresses.push(mapAddressFor);
    }//end for

    //Insert Images to Document
    for (i=1; i<=48; i++) {
        document.getElementById("hour" + i*6 + "map").src = mapAddresses[i-1];
    }//end for

How can I get rid of this error? I can't figure our why there's an error, and how can I fix it?

You create 40 elements:

for (var i = 1; i <= 40; i++) {
    // ...
    img.id = "hour" + index + "map";
    // ...
}//end for

and try to set 48

for (i=1; i<=48; i++) {
    document.getElementById("hour" + i*6 + "map").src = mapAddresses[i-1];
}//end for

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