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

时间:2018-09-03 01:45:28

标签: javascript for-loop scope iife

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应该(从摄像机)检索图像的网址,并将其附加到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>

1 个答案:

答案 0 :(得分: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>