2013-09-26 223 views
-1

我需要创建一个按钮点击链接,并点击同样的链接。我测试的创建一个链接,并点击一个按钮点击

<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(制作下载按钮,链接可能会有所不同)。有没有其他的方式来做到这一点?

我refferd:How do I programmatically click a link with javascript?

How do I create a link using javascript?

为实现这一点,但没有成功。

+1

你正在尝试getElementById(链接),但“链接”不是一个Id,它是一个元素。给链接一个id然后使用该id来获取它并点击()。 – nebulae

+0

为什么你需要创建并点击链接?如果你已经有了URL,那么你可以将'window.location'设置为那个URL? – David

回答

2

看来你真的只是想改变页面的位置,而不是实际追加的链接都:

location.href = 'your link you got back' 

如果你真的想在页面上添加一个物理链路:

var link=document.createElement("a"); 
link.id = 'someLink'; //give it an ID! 
link.href="http://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using- javascript"; 

//Add the link somewhere, an appendChild statement will do. 
//Then run this 
document.getElementById('someLink').click(); 
+0

我需要appendChild,它现在工作:)谢谢:) –