JS for -loop 总是使用最后一个元素 - 范围问题

JS for -loop always use last element - scope issues

var url_array = ["ulr1", "ulr2", "ulr3", "ulr4", "ulr5"];

var img = document.createElement('img');

for (i = 0; i < url_array.length; i++){
    var div = document.createElement('div');
    div.setAttribute("id", "div"+i);
    document.getElementById('main').appendChild(div);

    document.getElementById('div'+i).style.width = ImageWidth+5+"px";
    document.getElementById('div'+i).style.height = ImageHeight+5+"px";

    console.log("\ncreate all the DIVs. \nFor loop count: "+i);

    img.src = loadImage(url_array[i], ImageWidth, ImageHeight);

    try{throw img}
    catch(c_img) {

        document.getElementById('div'+i).appendChild(c_img);

        console.log("after load, and append, in Catch: "+img.src);
        console.log("div NR = "+document.getElementById('div'+i).id);
        console.log(document.getElementById('div'+i).childNodes.length);
    } //catch
} // FOR

function loadImage(URL, h, w)
{
    console.log("loadImage callaed with URL = "+URL);
    return url = URL+Date.now().toString(10);
}

For-Loop 应该检索图像(来自相机)的 url 地址并将它们附加到 DIV。 DIV 和 IMG 是即时创建的。问题是只有最后 DIV 成为图像持有者。

我正在使用 catch-try 强制立即执行代码,因此每个单独的 Div+i 都会有独特的图像。也像这样构造(立即调用函数表达式):

(function(){
  something here;
  })();

创建 "private" 范围没有希望。 "Let" - 应该在本地定义变量没有帮助。 *我在这里的知识有限,我依赖于网站上的数据(如果不违反规则,可以稍后提供link)。

console.log() 的输出没有多大帮助。 一切都按预期进行,除了 childNodes.length 每个 for-loop 迭代都是 1 - 这意味着每个 DIV 都有它的 IMG child 我猜......如果是这样 -为什么我看不到它们?

我觉得我已经接近我想要实现的目标 - 使用 Intervals() 刷新每个 DIV 新的相机快照,但我需要解决当前的问题。

可供使用的代码示例: js.js:

var url_array = [
"https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg",
"https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg",
"https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg"
];

var ImageWidth = 640;
var ImageHeight = 480;

var img = document.createElement('img');

for (i = 0; i < url_array.length; i++){

    var div = document.createElement('div');//.setAttribute("id", "div0");
    div.setAttribute("id", "div"+i);
    document.getElementById('main').appendChild(div);

    document.getElementById('div'+i).style.width = ImageWidth+5+"px";
    document.getElementById('div'+i).style.height = ImageHeight+5+"px";
    var color = ((Math.floor(Math.random() * (16777215)) + 1).toString(16)); // from 1 to (256^3) -> converted to HEX
    document.getElementById('div'+i).style.background = "#"+color;


    document.getElementById('div'+i).style.width = ImageWidth+5+"px";
    document.getElementById('div'+i).style.height = ImageHeight+5+"px";

    console.log("\ncreate all the DIVs. \nFor loop count: "+i);

    img.src = loadImage(url_array[i], ImageWidth, ImageHeight);

    try{throw img}
    catch(c_img) {

        document.getElementById('div'+i).appendChild(c_img);

        console.log("after load, and append, in Catch: "+img.src);
        console.log("div NR = "+document.getElementById('div'+i).id);
        console.log(document.getElementById('div'+i).childNodes.length);
    } // catch
} // FOR

function loadImage(URL, h, w)
{
    console.log("loadImage callaed with URL = "+URL);
    return url = URL+"?auto=compress&h="+h+"&w="+w;
}

HTML:

<html>
<head>
<meta charset="utf-8">
<STYLE>

div#main {
    padding: 5px;
    background: black;
}
</STYLE>
</head>
<body>



<script type="text/javascript">

function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
<div id="main"></div>
</body>
</html>

问题是你的

var img = document.createElement('img');

循环之外 - 你只会创建一个 img。当在 DOM 中已经存在的元素上调用 appendChild 时(例如在第二次、第三次、第四次等迭代中),该元素被 removed从它以前的位置插入到新位置。

改为在循环内创建图像,并尽量不要隐式创建全局变量 - 声明新变量时,始终使用 letconst.

此外,当你这样做时

var div = document.createElement('div');

您有对刚创建的 div 的引用 - 无需为它分配 id 即可 select 它与

document.getElementById('div'+i)

在下面的行中 在相同的范围内。相反,只需继续引用 div:

const ImageWidth = 200;
const ImageHeight = 200;
const main = document.getElementById('main');
var url_array = ["ulr1", "ulr2", "ulr3", "ulr4", "ulr5"];

for (let i = 0; i < url_array.length; i++){
  const img = document.createElement('img');
  const div = document.createElement('div');
  main.appendChild(div);
  div.style.width = ImageWidth+5+"px";
  div.style.height = ImageHeight+5+"px";
  img.src = loadImage(url_array[i], ImageWidth, ImageHeight);
  div.appendChild(img);
}
console.log(main.innerHTML);

function loadImage(URL, h, w) {
  return URL+Date.now().toString(10);
}
div#main {
    padding: 5px;
    background: black;
}
<div id="main">
</div>