将动态创建的图像替换为输入中的新图像

Replace dynamically created image for new image from input

本文关键字:图像 新图像 动态 创建 替换 输入      更新时间:2023-09-26

我应该在用户插入其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/

有人可以给我一个提示如何解决这个问题吗?我试图通过阅读"类似"问题来理解,但我没有找到任何可以解决我的情况的问题。

无论如何,谢谢你。

希望这个片段会有用

.HTML

  <input type ="text" id="imageIp" placeholder="New Image url"> <button id ="changeDisplay" > Change Display </button>
<div class ="demoDiv" id = "demoDiv">
</div>

.CSS

.demoDiv{
  margin-top:10px;
  height:300px;
  width:300px;
  background-image: url("http://freebigpictures.com/wp-content/uploads/shady-forest.jpg");

.JS

var getButton = document.getElementById("changeDisplay");
getButton.addEventListener('click',function(){
var getNewImage = document.getElementById("imageIp").value;
console.log(getNewImage);
document.getElementById("demoDiv").style.backgroundImage = "url('"+getNewImage+"')";
})

工作示例

编辑

在最新的代码段中,您尚未定义这两个数组

imageArray 
captionArray

您需要先定义它们,然后才能在其中推送内容。我已经在开始时初始化了它,但您可以相应地放置它们。但是,必须先初始化它们,然后才能在其中放置内容。

var getBtn = document.getElementById("btn");
var imageArray = []; // Initializing imageArray
var captionArray=[]; // Initializing captionArray
getBtn.addEventListener('click', function() {
// rest of code
))

注意:同样在您的代码片段中,没有 id menu 的 HTML 元素,因此当我运行此代码时,它抛出了错误。

使用提供的代码的工作示例