我应该在用户插入其URL后显示图像。它在第一次点击时效果很好,但是当用户输入一个新的URL时,用新的URL替换之前的图像,而不是在前一个图像下创建一个新图像。从输入替换为新图像动态创建的图像
这是我的功能至今:
HTML:
<p id="tt">Display an image using the image's URL</p>
<label>URL:
<textarea rows="1" cols="40" placeholder="Image URL" id="url"></textarea>
</label><br>
<label>Caption:
<textarea rows="1" cols="40" placeholder="Image caption" id="caption"></textarea>
</label><br>
<button id="btn">Add Image</button>
<br>
<div id="imgDiv"></div>
JS:
var getBtn = document.getElementById("btn");
getBtn.addEventListener('click', function() {
var figure = document.createElement("figure");
var image = document.createElement("IMG");
var figcaption = document.createElement("figcaption");
//attributing the input value in the first textarea as source for the image to be displayed
var url = document.getElementById("url").value;
image.src = url;
image.height = "200";
image.id = "newImage";
figure.appendChild(image);
//making the image a link to its url
var a = document.createElement("a");
a.href = url;
a.appendChild(image);
figure.appendChild(a);
//creating a Node and setting the input value from the second textarea as caption
var caption = document.getElementById("caption").value;
var text = document.createTextNode(caption);
document.getElementById("imgDiv").appendChild(figure);
figure.appendChild(figcaption);
figcaption.appendChild(text);
document.getElementById("menu").add(option);
//clear textarea after submitting url and caption
document.getElementById("url").value = "";
document.getElementById("caption").value = "";
});
编辑 - 的jsfiddle:https://jsfiddle.net/hpnLycer/4/
有人可以给我一个提示如何解决这个? 我试着通过阅读“类似”的问题来理解,但是我没有发现任何可以解决我的问题的方法。
无论如何谢谢你。
你能提供一个JSFiddle吗? –
图片很难跟踪;例如,它们不可搜索。 –
请创建一个[最小,完整和可验证的示例](http://stackoverflow.com/help/mcve),以便人们可以帮助 –