jquery或html下载图片onclick或链接 [英] jquery or html to download image onclick or with link

查看:108
本文介绍了jquery或html下载图片onclick或链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当目前点击时,下载框会随着弹出



我使用的是HTML:

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

这很好,但我有很多图片,有没有一种方法可以用jQuery来做类似于

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

可以下载图片,而无需两次输入,因此它看起来像这样:

 < a href =下载>< img src =folio / 1.jpg/>< / a> 

我试图简化编码,以便轻松点击图片到
下载它,而不是必须点击右键来保存它。



感谢您的帮助。

解决方案

这将适用于您的网页上的每一张图片,这是图片的直接子元素,但您可以使用:

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

但它可以胜任。

但唯一的事情是,JS禁用的用户会看到一个空href的锚。以下内容可以达到相同的最终结果,并且可以简化代码(更清晰的HTML)并增加优雅的降级:

 << ; img src =folio / 1.jpgclass =downloadable/> 

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

查看实际情况: http://jsfiddle.net/MW9E4/1/


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.

解决方案

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/

这篇关于jquery或html下载图片onclick或链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆