我想用javascript更改download
属性的值,我正在尝试使用download
标记的<a>
属性。但我不知道如何在download
中包含javascript?
<a href="REALFILENAME.txt" download="JAVASCRIPT_FUNCTION_HERE">CLICK ME</a>
function getDownloadName(){
return "REALFILENAME_" + new Date().getTime();+ ".txt";
}
谢谢!
答案 0 :(得分:1)
您可以使用setAttribute设置下载属性,如下所示:
function getDownloadName(){
return "REALFILENAME_" + new Date().getTime();+ ".txt";
}
function setDownloadAttribute() {
var a = document.getElementById("fileLink");
a.setAttribute("download", getDownloadName())
}
var a = document.getElementById("fileLink");
a.onclick = setDownloadAttribute;
答案 1 :(得分:0)
前提是我已正确理解您的问题。您需要为anchor
个元素href
元素添加click
事件处理程序。然后操纵anchor
的{{1}}值并设置addEventListener
属性(仅限HTML5)。我不相信你真的想要download
属性中包含的Javascript代码吗?
var out = document.getElementById('out');
// add a click event handler to all anchor elements on the page
[].forEach.call(document.getElementsByTagName('a'), function (element) {
element.addEventListener('click', function (e) {
var download = e.target.href.split('.').join('_' + new Date().getTime() + '.');
// the following line is what would be used, HTML5
e.target.download = download;
// the following lines are added to show you what is happening,
// prevent the event downloading and output the download URL
e.preventDefault();
out.textContent += download + '\n';
}, false);
});
<a href="REALFILENAME.txt">CLICK ME</a>
<pre id="out"></pre>