我應該在用戶插入其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),以便人們可以幫助 –