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

时间:2015-02-10 09:42:05

标签: javascript html download rename

我想用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";
}

谢谢!

2 个答案:

答案 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;

jsFiddle

答案 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>