从onclick方法调用href不起作用

问题描述 投票:0回答:4

您好我想知道如何从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;
        }

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

javascript download href
4个回答
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>

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
投票

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

例:

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

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


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>
© www.soinside.com 2019 - 2024. All rights reserved.