从onclick方法调用href无效

时间:2019-02-14 10:39:11

标签: javascript download href

您好,我想知道如何从a button事件中调用onclick点击:

到目前为止,我已经可以使用这两种方法进行工作了:

<a class="button" type="application/octet-stream"  href="http://localhost:5300/File" download>Click here for dld</a>

<input type="button"  onclick="location.href='http://localhost:5300/File';" value="Download"/>

但是我无法使其与js一起使用;我曾这样尝试过:

 <button  onclick="Save('http://localhost:5300/File')">Download</button>

 function Save(url){
            var link=document.createElement('a');
            link.url=url;
            link.name="Download";
            link.type="application/octet-stream";
            document.body.append(link);
            link.click();
            document.body.removeChild(link);
            delete link;
        }

PS 我需要使用<button></button>而不是input

4 个答案:

答案 0 :(得分:1)

添加button type='button'

function Save(url) {
  console.log(url)
  var link = document.createElement('a');
  link.url = url;
  link.name = "Download";
  link.type = "application/octet-stream";
  document.body.append(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}
<a class="button" type="application/octet-stream" href="http://localhost:5300/File" download>Click here for dld</a>



<button type='button' onclick="Save('http://localhost:5300/File')">Download</button>

答案 1 :(得分:1)

您实际上是否需要创建一个a元素?如果没有,我将使用window.location.href,类似于单击链接。

示例:

function Save(url){
    window.location.href = url;
}

唯一的问题可能是您要从HTTPS(安全)站点链接到HTTP(非安全)站点。

答案 2 :(得分:1)

您的代码创建一个链接,单击它然后将其删除。您可以像在HTML示例中一样运行window.location.href

onclick = "Save('http://localhost:5300/File')" > Download < /button>

function Save(url) {
  window.location.href = url;
}
<button onclick="Save('http://localhost:5300/File')">Download</button>

或者,如果您坚持使用创建链接的方法,则应为链接设置href,而不是url

function Save(url) {
  var link = document.createElement('a');
  link.href = url;
  link.name = "Download";
  link.type = "application/octet-stream";
  document.body.append(link);
  link.click();
  document.body.removeChild(link);
}
<button onclick="Save('http://localhost:5300/File')">Download</button>

答案 3 :(得分:0)

const btn = document.querySelector('button');
btn.addEventListener('click', function(e) {
    e.preventDefault();
    save('http://localhost:5300/File');
});

function save(url) {
    let link = document.createElement('a');
    link.href = url;
    link.name = "Download";
    link.type = "application/octet-stream";
    document.body.append(link);
    link.click();
    document.body.removeChild(link);
    delete link;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Download</button>