如何在动态添加时在html中使用换行标记

时间:2012-10-13 10:41:18

标签: javascript 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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

上面的代码是正确的,问题是&#34; appendChild&#34;,请找到下面的工作代码:

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