Javascript DOM将图像数组加载到div背景中?

时间:2013-03-19 01:14:17

标签: javascript image dom html tags

基本上我在名为image0.png, image1.png, image(index).png的文件夹中有图像,我想加载这些图像(预加载,因此它们不会在页面加载后永远无法加载)到div中的图像标记中。图像标记由DOM生成,然后初始化为默认参数。我遇到的问题是,我似乎无法让Document模型将数组充满图像并将其加载到图像标记IMGTG.src = IMGS[0];中?下面是代码

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">

IMGS = new Array(); 
var IMGTG;

function INIT_IMGTG(id)
{       
    IMGTG = document.createElement("img");      
    IMGTG.setAttribute("height", "100%");
    IMGTG.setAttribute("width", "100%");    
    IMGTG.setAttribute("border", "0");      
} 
function LOAD_IMGS() 
{    
    var index = 0;              

    for(index = 0; i < 2; i++) 
    {               
        IMGS[i] = "image" + index + ".png"
    }            
}  
function IMG_ARY(id) 
{
    LOAD_IMGS();    
    INIT_IMGTG(id); 

    IMGTG.src = IMGS[0];        
}
</script>
</head>
<body onload = "IMG_ARY('IMG_ID')">
<div id="IMG_ID"></div>
</body>
</html>

修改 到目前为止,我对两位回答者进行了如下所述的编辑,但仍然没有运气?我不确定是什么,Javascript是一种古怪的语言。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">

IMGS = new Array(); 
var IMGTG;

function INIT_IMGTG(id)
{       
    IMGTG = document.createElement("img");      
    IMGTG.setAttribute("height", "100%");
    IMGTG.setAttribute("width", "100%");    
    IMGTG.setAttribute("border", "0");  
    id.appendChild(IMGTG);
} 
function LOAD_IMGS() 
{    
    for(var i = 0; i < 2; i++)
    {               
        IMGS[i] = "image" + i + ".png";
    }        
}  
function IMG_ARY(id) 
{
    LOAD_IMGS();    
    INIT_IMGTG(id); 

    IMGTG.src = IMGS[0];        
}
</script>
</head>
<body onload = "IMG_ARY('IMG_ID')">
<div id="IMG_ID"></div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

看起来您已正确设置了图片srcIMGTG)以及它的其他属性,但您实际上并未将其插入DOM中。

尝试将其添加到IMG_ARY的底部:

id.appendChild(IMGTG);

答案 1 :(得分:1)

似乎与for循环一致iindex互换,但只声明了index

变化

var index = 0;              

for(index = 0; i < 2; i++) 
{               
    IMGS[i] = "image" + index + ".png"
}    

for(var i = 0; i < 2; i++)
{               
    IMGS[i] = "image" + i + ".png";
}