How can I dynamically create an unordered list in JavaScript?

前端 未结 4 2044
梦谈多话
梦谈多话 2021-01-12 00:28

I have a global JavaScript array that contains some strings.

I want to create a dynamic list based on the strings in my JavaScript array. Similar to this:

         


        
相关标签:
4条回答
  • 2021-01-12 00:30

    Try this

    var str = '<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>';
    
    for(var i in $yourArray){
       str += '<li><a href="#">String 1</a></li>';
    }
    
    str += '</ul>';
    
    $('body').append(str);
    
    0 讨论(0)
  • 2021-01-12 00:37
    var $bread = $('ul.xbreadcrumbs');
    $.each(yourArray, function(index, value) {
      $('<li><a href="#">' + value + '</a></li>')
        .appendTo($bread);
    });
    

    I have not tested this - just off my head. Hope this helps!

    0 讨论(0)
  • 2021-01-12 00:47

    Yes you can. You can either user the DOM directly with createElement (see Jonathan's answer), or go an very easy route with jQuery (not tested):

    var ul = "<ul>";
    for(var i=0; i < arr.length; i++) {
        ul += "<li><a href=\"#\">" + arr[i] + "</a></li>";
    }
    ul += "</ul>";
    
    var ulElem = $(ul);
    
    0 讨论(0)
  • 2021-01-12 00:48

    If you only need a flat array (i.e. not multi-dimensional and no arrays within the array), then you can do the following in plain JavaScript:

    var strs = [ "String 1", "String 2", "String 3" ];
    var list = document.createElement("ul");
    for (var i in strs) {
      var anchor = document.createElement("a");
      anchor.href = "#";
      anchor.innerText = strs[i];
    
      var elem = document.createElement("li");
      elem.appendChild(anchor);
      list.appendChild(elem);
    }
    

    Then append list to whichever parent element in the body you desire.

    0 讨论(0)
提交回复
热议问题