Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

javascript - jquery or html to download image onclick or with link

I have an image that I want the user to click on to be able to download ( save it ).

When currently clicked, the download box pops up with the image.jpg tag and lets the user save it.

I am using HTML:

<a href="folio/1.jpg" download><img src="folio/1.jpg"/></a>

This works well, but I have a lot of images, is there a way to use jQuery to do something like

jQuery(function($){
$("a").prop("href", "(this)")
});

to download the image without having to type it in twice so it looks like this:

<a href="" download><img src="folio/1.jpg"/></a>

I am trying to simplify the coding to make it easy to click on the image to download it rather than to have to right click to save it.

Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This would apply to every single image on your page which is the direct child of an anchor, but you could use:

$('a > img').each(function(){
  var $this = $(this);
  $this.parent('a').attr('href', $this.attr('src'));
});

But it would do the job.

Only thing is though, users with JS disabled will see an anchor with an empty href. The following would achieve the same end result with the added benefit of simplifying your code (cleaner HTML) and adding graceful degradation:

<img src="folio/1.jpg" class="downloadable" />

and

$('img.downloadable').each(function(){
  var $this = $(this);
  $this.wrap('<a href="' + $this.attr('src') + '" download />')
});

See it in action: http://jsfiddle.net/MW9E4/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...