2012-10-13 23 views
3

我面臨的問題是我想要換行符
在代碼中動態添加的標籤在第一個標記爲錨點後永遠不會工作 我希望每個鏈接都動態添加應該去上新的生產線如何在html中動態添加換行符標籤時工作

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 

<script> 
function addAnchorNode(){ 
    var link = document.createElement('a'); 
    link.setAttribute('href', 'http://Google.co.uk'); 
    link.innerHTML = "Hello, Google!"; 

    document.body.appendChild(link); 
    document.body.appendchild(document.createElement('br')); //Never Works 
} 
</script> 
</head> 

<body> 
<button onclick="addAnchorNode()">Click me</button> 
</body> 
</html> 
+2

'document.body的。 appendchild(document.createElement('br'));'說沒有方法'appendchild'。它應該是'appendChild'。 – whirlwin

回答

3

你必須有你的BR之後的東西,並沒有錯字(「使用appendChild」,而不是「使用appendChild」)。

這工作:

function addAnchorNode(){ 
    var link = document.createElement('a'); 
    link.setAttribute('href', 'http://Google.co.uk'); 
    link.innerHTML = "Hello, Google!"; 

    document.body.appendChild(document.createElement('br')); 
    document.body.appendChild(link); 
} 

demonstration

+0

非常感謝您的回答,而我在您使用代碼時所做的建議與我們所做的一樣,甚至可以達到期望的結果,即每個新鏈接都將進入新行。告訴我爲什麼我們不能放置這個document.body.appendChild(document.createElement('br'));錨點標記後的 document.body.appendChild(link); 爲什麼我們必須在錨標籤之前做到這一點 –

0

上面的代碼是正確的,問題是 「使用appendChild」,請看以下工作代碼:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 

<script> 
function addAnchorNode(){ 
    var link = document.createElement('a'); 
    link.setAttribute('href', 'http://Google.co.uk'); 
    link.innerHTML = "Hello, Google!"; 

    document.body.appendChild(link); 
    document.body.appendChild(document.createElement("br")); 
    //document.body.appendchild(document.createElement('br')); //Never Works 
} 
</script> 
</head> 

<body> 
<button onclick="addAnchorNode()">Click me</button> 
</body> 
</html>