开发者

Append anchor tags to list html

开发者 https://www.devze.com 2023-04-12 16:43 出处:网络
In my javascript am trying to 1) make a new li tag 2) make a new a (anchor tag) 3) append the anchor tag to li tag

In my javascript am trying to

  • 1) make a new li tag
  • 2) make a new a (anchor tag)
  • 3) append the anchor tag to li tag
  • 4) set the text for anchor tag (so that someone can click on it)
  • 5) set onClick event function for anchor tag (to be called when click is made in 4))
  • 6) append the li tag to a div

    And h开发者_运维技巧ere is my code :

    var newLi = document.createElement('li');
    var newA = document.createElement('a');
    newLi.appendChild(newA);
    //newA.href='#';
    newA.innerText = "Go here";
    newA.onClick = function(){
                          // do something here
                  }
    document.getElementById('map_canvas').appendChild(newLi); 
    

    Obviusly it is not working and all I see is Just the bullets(as below) on my page with no text and clickable text (for anchor tags) <li> <li>


    just use innerHTML instead of innerText


    I'd suggest using .innerHTML in place of .innerText, and ideally creating a function:

    function listLinks(listId, url,text){
    
        var linkList;
        if (document.getElementById(listId)) {
            linkList = document.getElementById(listId);
        }
        else {
            linkList = document.createElement('ul');
            document.body.appendChild(linkList);
        }
        var newA = document.createElement('a');
    
        newA.innerHTML = text;
        newA.href = url;
        newA.onclick = function(){
            this.style.color = '#f00'; // or whatever...
            return false;
        };
    
        var newLi = document.createElement('li');
    
        newLi.appendChild(newA);
    
        linkList.appendChild(newLi);
    }
    
    // call as:
    listLinks('links','http://google.com/','Google');
    

    JS Fiddle demo.

  • 0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    关注公众号