javascript - 画布没有附加到列表中
问题描述
我有两个 dataUrls 需要显示在画布中,最后我希望将它们附加到名为 "piclist" 的无序列表中。但我只能看到附加了一张图片。有人能告诉我为什么没有附加另一张图片吗?我还检查了一条警告消息,循环是否被迭代了两次并且确实如此。但只附加了图片
let datapo = {{datapo|safe}};
for (var key in datapo) {
//alert(key+" "+datapo[key]);
var node = document.createElement("li");
var d0 = document.createElement("div");
var c = document.createElement("canvas");
var c4 = c.getContext("2d");
c.width = 200; // in pixels
c.height = 100; // in pixels
var myImg = new Image;
myImg.src = datapo[key];
myImg.width = c.width;
myImg.height = c.height;
myImg.onload = () => { c4.drawImage(myImg, 0, 0, c.width, c.height);
document.body.appendChild(c); // adds the canvas to the body element
node.appendChild(c);
document.getElementById("piclist").append(node);
};
}
解决方案
同一个元素不能在 DOM 中追加两次,解决方案是在插入第二个位置之前克隆元素,参见演示
function myFunctionNotWorking() {
var node = document.createElement("LI");
var textnode = document.createTextNode("Item");
node.append(textnode);
node.append(textnode);
node.appendChild(textnode);
document.getElementById("myList").append(node);
document.getElementById("myList").append(node);
document.getElementById("myList").appendChild(node);
}
function myFunctionWorking() {
var node = document.createElement("LI");
var textnode = document.createTextNode("Item");
node.append(textnode);
node.append(textnode.cloneNode(true));
node.appendChild(textnode.cloneNode(true));
document.getElementById("myList").append(node);
document.getElementById("myList").append(node.cloneNode(true));
document.getElementById("myList").appendChild(node.cloneNode(true));
}
<ul id="myList">
<li>Item</li>
</ul>
<p>Click the button to append an items to the end of the list.</p>
<button onclick="myFunctionNotWorking()">Add Items (not working)</button>
<button onclick="myFunctionWorking()">Add Items (working)</button>
推荐阅读
- angular - 我想显示来自 firestore 的数据,但我收到错误 Spread types may only be created from object types
- reactjs - 如何在 const 中插入另一个 CSS 并在 reactjs 中从另一个 const 调用
- behavior - 如何使用行为更改按钮背景?
- db2 - DB for z/OS 中的递归查询
- excel - 如何在不更改的情况下将 csv 表复制到 excel 文件中
- django - Django ArrayAgg - 过滤带注释的数组
- django - 使用 Jinja 返回一个组的总和
- amazon-web-services - AWS copilot 部署的服务不可访问?
- bash - 检查 openssl 会导致字典攻击
- python - pandas聚合函数的模棱两可的行为