我认为这是非常基本的。不过,我的javascript上有点生疏,所以我甚至可能找不到适合自己问题的地方。我有两个非常相似的数组。我有一个“if语句”,用于验证在“for循环”中使用哪个数组。为此,我认为将所需的数组分配给新名称是最简单的。因此:
<body>
<div id="dataLocation">
</div>
<script type='text/javascript'>
oldArray1 = [["name11",51,61,"page11.html"],["name12",151,161,"page12.html"]];
oldArray2 = [["name21",61,71,"page21.html"],["name22",161,171,"page22.html"]];
function loadArray(type){
var compiledData = "", newArray = new Array();
if(type=="a") newArray.push(oldArray1);
else newArray.push(oldArray2);
for(i=0;i<newArray.length;i++){
compiledData += "<a href='" + newArray[i][3] + "'><img src='img.png' title='" + newArray[i][0] + "' style='position: absolute; z-index: 3; left: " + newArray[i][1]-1 + "px; top: " + newArray[i][2]-1 + "px;'></a>";
}
document.getElementById('dataLocation').innerHTML = compiledData;
}
window.onload = loadArray("a");
</script>
</body>
Currenlty页面在Firebug中运行时没有错误并返回结果:
NaNpx;'&GT;
这似乎来自compiledData的最后一部分。它应该返回一些链接的图像。当我在firebug中执行console.log时,它将newArray显示为字符串,同时将oldArray1显示为数组,所以我猜我的问题就在那里。
请原谅我的无知,非常感谢任何帮助。
答案 0 :(得分:0)
分配数组的问题
if(type=="a") newArray = oldArray1;
else newArray = oldArray2;
以及for循环,您必须将此部分left: " + newArray[i][1]-1 + "px; top: " + newArray[i][2]-1 + "px;'
更改为
compiledData += "<a href='" + newArray[i][3] + "'><img src='img.png' title='" + newArray[i][0] + "' style='position: absolute; z-index: 3; left: " + newArray[i][1] + "px; top: " + newArray[i][2] + "px;'></a>";
编辑
var left_val = newArray[i][1] - 1;
var top_val =newArray[i][2] - 1;
compiledData += "<a href='" + newArray[i][3] + "'><img src='img.png' title='" + newArray[i][0] + "' style='position: absolute; z-index: 3; left: " + left_val + "px; top: " + top_val + "px;'></a>";