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

问题描述 投票:1回答:1
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;
  })();

创建“私人”范围没有希望。 “Let” - 本应在本地定义变量并没有帮助。 *我的知识有限,我依赖于网站上的数据(如果不符合规则,可以在以后提供链接)。

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

我觉得我接近我想要实现的目标 - 使用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>
javascript for-loop scope iife
1个回答
1
投票

问题是你的

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

在循环之外 - 你只创造一个img。当在DOM中已经存在的元素上调用appendChild时(例如在第二次,第三次,第四次等迭代中),元素将从其先前位置移除并插入到新位置。

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

而且,当你这样做

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

你有一个你刚刚创建的div的引用 - 没有必要为它选择一个id来选择它

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>
© www.soinside.com 2019 - 2024. All rights reserved.