从 onclick 方法调用 href 不起作用

Calling href from onclick method does not work

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

到目前为止,我已经使用这两种方法让它工作了:

<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;
        }

P.S 我需要使用 <button></button> 而不是 input !

添加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>

您真的需要创建一个 a 元素吗?如果没有,我会使用 window.location.href,这类似于单击 link。

示例:

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

唯一的问题可能是您 link 从 HTTPS(安全)站点访问 HTTP(非安全)站点。

您的代码创建了一个 link,点击它然后将其删除。您可以像在 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>

或者,如果您坚持创建 link 的方法,则应该为 link 设置 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>

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>