动态创建链接Javascript

mky*_*ong 14 javascript href createelement

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

Sim*_*röm 25

看看这个例子:

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
Run Code Online (Sandbox Code Playgroud)

  • 如果没有“var”,此代码将在全局范围内创建一个变量。因此,这段代码创建了一个“window.a”变量,其他任何人都可以在这段代码运行期间随时覆盖和修改该变量。 (2认同)

Gol*_*wby 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);
Run Code Online (Sandbox Code Playgroud)