使用 javascript 更改锚点的下载属性值

Changing the value of the download attribute of an anchor with javascript

我想用 javascript 更改 download 属性的值,我正在尝试使用 <a> 标签的 download 属性。但我不知道如何在 download?

中包含 javascript
<a href="REALFILENAME.txt" download="JAVASCRIPT_FUNCTION_HERE">CLICK ME</a>

function getDownloadName(){
    return "REALFILENAME_" + new Date().getTime();+ ".txt";
}

谢谢!

您可以使用 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;

jsFiddle

前提是我已经正确理解了你的问题。您需要添加一个 click event handler to you anchor elements ( addEventListener). Then manipulate the href value of the anchor and set the download 属性(仅限 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>