如何使用JS

时间:2018-06-15 09:42:26

标签: javascript html image innerhtml preload

我对这个问题感到困惑,并且试图让它发挥作用已经持续了2周。

我可以在HTML页面加载时预加载图像,但我无法访问图像,我收到以下错误:

http://localhost/taskB/html/html/members/[object%20HTMLImageElement] 404 (Not Found) [object%20HTMLImageElement]:1 GET

我的代码如下,预加载功能标记正确,但我无法弄清楚如何访问图像数组:

function preloaded() {
    var itemDesc = setDesc();
    var preload = new Array();
    var loadedimages = new Array();
    var countPreload = 0;
    for (var r = 1; r <= 4; r++) {
        for (var c = 1; c <= 5; c++) {
            preload[countPreload] = "../../images/slices/" + itemDesc + "/" + itemDesc + "_r" + r + "_c" + c + ".jpg";
            countPreload++;
        }
    }
    for (var i = 0; i<preload.length; i++){
        loadedimages[i] = new Image();
        loadedimages[i].src = preload[i];
    }
}

function buildImageHTML() {
    var itemDesc = setDesc(getUrlVars()["description"]);
    var countFile = 0
    var file = new Array();
    // START REDO the images for access
    var preload = new Array();
    var loadedimages = new Array();
    var countPreload = 0;    
    for (var r = 1; r <= 4; r++) {
        for (var c = 1; c <= 5; c++) {
            preload[countPreload] = "../../images/slices/" + itemDesc + "/" + itemDesc + "_r" + r + "_c" + c + ".jpg";
            countPreload++;
        }
    }
    for (var i = 0; i<preload.length; i++) {
        loadedimages[i] = new Image();
        loadedimages[i].src = preload[i];
    }
    //END REDO the images for access
    var writeThis = "";
    writeThis += "<table>";

    //Build Rows then columns
    for (var x = 1; x <= 4; x++) {
        writeThis += "<tr>";
        //Loop through and add five <td> cells to hold the image slices
        for (var y = 1; y <= 5; y++) {
            file = loadedimages[countFile];
            writeThis += "<td><img src=\"" + file + "\"></td>";
            countFile++;
        }
        writeThis += "</tr>";
    }
    writeThis += "</table>";
    var divImageObj = document.getElementById('divImageObject');
    divImageObj.style.display = 'block';
    divImageObj.innerHTML = writeThis;
}

我还有一个名为start()的函数:

function start() {
    preloaded();
}

我通过start事件调用onload函数,如下所示:

<body onload="start();">

要求是我必须使用innerHtml来渲染图像。

这里有任何指示都很棒。

1 个答案:

答案 0 :(得分:2)

loadedimages是图像对象的数组。请使用loadedimages [countFile] .scr。

file = loadedimages[countFile].src;

最好从HTML head部分调用preloaded()。在渲染所有页面之后,onload事件会在很晚之后触发。

<html>
<head>
...
<script>
preloaded();
</script>
</head>
<body>
...