您好我想知道如何从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
!
您的代码会创建一个链接,单击它然后将其删除。您可以像在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>
添加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
,这类似于点击链接。
例:
function Save(url){
window.location.href = url;
}
唯一的问题可能是您从HTTPS(安全)站点链接到HTTP(非安全)站点。
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>