当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Hyperlink downloads whatever that img src is

问题描述:

Alright i can't really seem to find anything regarding EXACTLY what i'm doing.

Anyways i need to set a hyperlink to download an image. That image has an id already.

Everytime the user displays an image, the download link will download that image they have entered.

When you run the code, enter 255812 for image code.

function myFunction() {

var x = document.getElementById("imagetxt").value;

var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";

// Creating an image

var img = new Image();

// Defining the function if image loads successfully.

img.onload = function() {

document.getElementById("image1").src = y;

};

//Defining the function if image fails to load.

img.onerror = function() {

alert("Image not found");

};

img.src = y;

}

<body align="center">

<div>

<img src="http://i.imgur.com/dXo8Fxp.png" width="20%" height="20%">

</div>

<div>

<img src="http://i.imgur.com/jCOLCiU.png" width="8%" height="8%">

</div>

<div>

<input id="imagetxt" size="6" type="text" value="">

</div>

<div>

<input id="btn1" type="button" value="Display" onclick="myFunction()" style="top: 5px; position: relative;">

</div>

<div>

<img id="image1" src="" width="30%" height="30%" style="top: 10px; position: relative;">

</div>

<a href="???" id="imageDL" onclick="??">DOWNLOAD THIS</a>

网友答案:

Get rid of the onclick on the anchor tag

 <a href="#" id="imageDL" download>DOWNLOAD THIS</a>

Set the anchor's href in the img.onload

img.onload = function() {
    document.getElementById("image1").src = y;
    document.getElementById("imageDL").href = y;
};
网友答案:

Add this to the end of myFunction

document.getElementById("imageDL").href = y;

function myFunction() {
  var x = document.getElementById("imagetxt").value;
  var y = "http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + x + ".jpg";

  // Creating an image
  var img = new Image();

  // Defining the function if image loads successfully.
  img.onload = function() {
    document.getElementById("image1").src = y;
  };

  //Defining the function if image fails to load.
  img.onerror = function() {
    alert("Image not found");
  };
  img.src = y;
  
  document.getElementById("imageDL").href = y;
}
<body align="center">
  <div>
    <img src="http://i.imgur.com/dXo8Fxp.png" width="20%" height="20%">
  </div>
  <div>
    <img src="http://i.imgur.com/jCOLCiU.png" width="8%" height="8%">
  </div>
  <div>
    <input id="imagetxt" size="6" type="text" value="">
  </div>
  <div>
    <input id="btn1" type="button" value="Display" onclick="myFunction()" style="top: 5px; position: relative;">
  </div>
  <div>
    <img id="image1" src="" width="30%" height="30%" style="top: 10px; position: relative;">
  </div>
  <a href="???" id="imageDL" onclick="??">DOWNLOAD THIS</a>
分享给朋友:
您可能感兴趣的文章:
随机阅读: