【发布时间】:2021-01-14 00:08:15
【问题描述】:
我需要在按钮单击时创建一个链接,并通过相同的单击单击该链接。我正在测试
上提到的方法<script type="text/javascript">
function download()
{
alert("Hello");
var link=document.createElement("a");
link.href="https://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using- javascript";
document.getElementById(link).click();
// here it says "cannot click on null", means id is not link, then how can i obtain the id
alert("Hello again");
}
</script>
<button type ="button" value="Download" onClick="download();">Downloads</button>
我需要这个,因为单击按钮时,我将拨打 get 电话,我将收到一个 URL,然后我需要单击该 URL(制作下载按钮,链接可能会有所不同)。有没有其他方法可以做到这一点?
我转发:How do I programmatically click a link with javascript?
和
How do I create a link using javascript?
为了达到这个目的,但没有成功。
【问题讨论】:
-
您正在尝试 getElementById(link) 但“link”不是 Id,它是一个元素。给链接一个 id 然后使用该 id 来获取它并点击()。
-
为什么需要创建并点击链接?如果您已经拥有该 URL,那么您可以将
window.location设置为该 URL?
标签: javascript html