从输入替换动态创建的图像以获取新图像

时间:2016-01-20 04:57:19

标签: javascript dynamically-generated

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

有人可以给我一个提示如何解决这个问题吗? 我通过阅读“类似”问题尝试了解,但我找不到任何可以解决我案例的问题。

无论如何,谢谢你。

1 个答案:

答案 0 :(得分:0)

希望此代码段有用

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+"')";
})

WORKING EXAMPLE

修改

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

imageArray 
captionArray

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

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

// rest of code

))

注意:在您的代码段中也没有标识为menu的HTML元素,因此当我运行此代码时会抛出错误。

WORKING EXAMPLE WITH SUPPLIED CODE