【问题标题】:JS for -loop always use last element - scope issuesJS for -loop 总是使用最后一个元素 - 范围问题
【发布时间】:2019-02-08 01:44:05
【问题描述】:
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;
  })();

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

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>

【问题讨论】:

  • 可以创建一个易于调试的工作代码 sn-p...。

标签: javascript for-loop scope iife


【解决方案1】:

问题是你的

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

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

改为在循环内创建图像,并尽量不要隐式创建全局变量 - 声明新变量时,请始终使用 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>

【讨论】:

  • 有效!我有点羞于承认——我试图解决这个特殊问题 2 天。最初我认为创建 img 对象必须在外部完成 - 然后在 for 循环的每次迭代中动态更改 img 的内容。非常感谢您的帮助!
猜你喜欢
  • 2017-02-26
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多