无法找到Javascript错误的原因和解决方案

时间:2016-03-06 15:01:21

标签: javascript arrays for-loop error-handling src

当我运行我的代码时,出现错误:Cannot set property 'src' of null

错误出现在for循环中:

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

以下是导致这一点的所有代码:

<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

如何摆脱这个错误?我无法解释为什么会出现错误,我该如何解决?

1 个答案:

答案 0 :(得分:3)

您创建了40个元素:

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

并尝试设置48

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