javascript - 找不到Java错误的原因和解决方案

标签 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

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

最佳答案

您创建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

关于javascript - 找不到Java错误的原因和解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35828424/

相关文章:

c++ - 如何读取多行输入?

r - 对于 R 中的循环(意外的符号错误)

javascript - js函数调用一次后页面卡住

java - 如何在 Java 中将任何数组作为参数传递?

powershell - 使用 for 循环更改 pscustomobject 数组的值

c# - 为什么不能创建多维数组数组?

c - C 数组是动态的吗?

javascript - 在 Node.js 中使用远程图像提供动态生成的 PDF

javascript - 当页面加载时超时调用时,removeChild 不起作用

javascript - 斐波那契数列 - 仅添加奇数 - Javascript