动态创建链接Javascript [英] Dynamically Create Link Javascript

查看:94
本文介绍了动态创建链接Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的文本设置为链接,这样当我点击它时,它会运行一个函数。现在我只是将它设置为google.com以尝试将文本显示为链接,但它似乎根本没有做任何事情。这只是静态文本。有什么建议吗?

I'm trying to set my text as a link so that when I click on it, it runs a function. Right now I just have it set to google.com to try to get the text to appear as a link, but it doesn't seem to be doing anything at all. It's just static text. Any suggestions?

        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


推荐答案

看看这个例子:

http://jsfiddle.net/ajXEW/

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

I added some comments inside the code that explain the diffrent steps.

    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

这篇关于动态创建链接Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆