通过Javascript动态创建链接

14

我想把文本设置为链接,这样当我点击它时,它会运行一个函数。现在我只是将它设置为google.com,以尝试让文本显示为链接,但似乎什么也没有发生。它只是静态文本。有什么建议吗?

        var leftDiv = document.createElement("div"); //Create left div
        leftDiv.id = "left"; //Assign div id
        leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes
        leftDiv.style.background =  divColor;
        a = document.createElement('a');
        a.setAttribute('href', 'google.com');
        user_name = a.appendChild(document.createTextNode(fullName + ' '));

        leftDiv.appendChild(user_name); // Add name to left div

1
链接到另一个网站时,必须使用完整的URI/域名:google.com需要变成http://google.com,才能使href链接到Google。 - David Thomas
它仍然显示为静态文本而不是链接。 - mkyong
你从未将链接插入文档中,只有文本节点。a.appendChild返回刚刚添加的节点。 - Felix Kling
2个回答

27

看这个例子:

http://jsfiddle.net/ajXEW/

我在代码里添加了一些注释,用来解释不同的步骤。

    var leftDiv = document.createElement("div"); //Create left div
    leftDiv.id = "left"; //Assign div id
    leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes
    leftDiv.style.background =  "#FF0000";
    a = document.createElement('a');
    a.href =  'google.com'; // Insted of calling setAttribute 
    a.innerHTML = "Link" // <a>INNER_TEXT</a>
    leftDiv.appendChild(a); // Append the link to the div
    document.body.appendChild(leftDiv); // And append the div to the document body

为什么 a = document.createElement('a'); 不是 var a = document.createElement('a'); - JAT86
变量a和a是相同的,在JavaScript中var是可选的。 - Jin Thakur
2
没有使用 var,这段代码会在全局作用域中创建一个变量。因此,这段代码会创建一个 window.a 变量,任何人都可以在代码运行期间随时覆盖和修改它。 - Heretic Monkey

1
试一下这个:http://jsfiddle.net/HknMF/5/
var divColor = "red";
var fullName = "bob";

var leftDiv = document.createElement("div"); //Create left div
        leftDiv.id = "left"; //Assign div id
        leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes
        leftDiv.style.background =  divColor;
        a = document.createElement('a');
        a.setAttribute('href', 'google.com');
        a.appendChild(document.createTextNode(fullName + ' '));

        leftDiv.appendChild(a); // Add name to left div

    document.body.appendChild(leftDiv);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接