将“下载”属性添加到<a> dynamically using Jquery

时间:2016-06-27 18:12:57

标签: javascript jquery html5

I am trying to add the download attribute to an tag dynamically. Here is what I have so far:

$(fclass).append('<a href="/files/'+$days[$i][2][1]+'" download>'+$days[$i][2][0]+'</a>');

Which produces this:

<a href="/files/day0.pdf" download="">Slideshow (Notes)</a>

I also added the exact same tag as this produces into my HTML manually, but instead of

<a href="/files/day0.pdf" download="">

I used

<a href="/files/day0.pdf" download>

The manual version works perfectly, and automatically downloads the file, however, the dynamically placed version does not. I have also tried this:

$(a).attr("download","/files/day0.pdf");

But this does not seem to work. Any ideas on how to fix this? Thank you very much.

3 个答案:

答案 0 :(得分:5)

答案是

$("a").attr("download", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="file-to-download.txt">Download the file</a>

刚检查一下它是否正常工作:D

答案 1 :(得分:0)

我遇到了同样的问题,这对我有用:

$("a").replaceWith('<a href="/files/day0.pdf" download="day0.pdf">Slideshow (Notes)</a>');

download="day0.pdf"中的 day0.pdf 将是文件名。

(在Firefox中,您必须在名称中包含.pdf,但在Chrome中,则没有必要,它将包含扩展名。)

答案 2 :(得分:-1)

你尝试过使用道具吗?

&#13;
&#13;
$(a).prop("download","/files/day0.pdf");
&#13;
&#13;
&#13;