【问题标题】:Dynamically Create Link Javascript动态创建链接 Javascript
【发布时间】:2023-04-06 18:34:01
【问题描述】:

我正在尝试将我的文本设置为链接,以便当我单击它时,它会运行一个函数。现在我只是将它设置为 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

【问题讨论】:

  • 我认为,指向另一个站点的链接必须使用完整的 URI/域名:google.com 需要为 http://google.comhref 才能链接到 Google。
  • 它仍然显示为静态文本而不是链接。
  • 您永远不会将链接插入到文档中,只会插入文本节点。 a.appendChild 返回刚刚附加的节点。

标签: javascript href createelement


【解决方案1】:

看这个例子:

http://jsfiddle.net/ajXEW/

我在代码中添加了一些 cmets 来解释不同的步骤。

    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');
  • var a 和 a 相同 var 在 javascript 中是可选的
  • 如果没有var,此代码会在全局范围内创建一个变量。所以这段代码创建了一个window.a 变量,任何其他人都可以在这段代码运行期间随时覆盖和修改。
【解决方案2】:

试试这个: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);

【讨论】:

    猜你喜欢
    • 2017-10-11
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多