Динамически создать ссылку Javascript - PullRequest
13 голосов
/ 23 марта 2012

Я пытаюсь установить свой текст в виде ссылки, чтобы при нажатии на него запускалась функция. Сейчас я просто настроил 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

Ответы [ 2 ]

22 голосов
/ 23 марта 2012

Посмотрите на этот пример:

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
0 голосов
/ 23 марта 2012

Попробуйте: 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);
...