how to create a list of span for a given array

后端 未结 3 533
灰色年华
灰色年华 2021-01-21 08:58

Let\'s say I have an object which looks like that:

var users = [\'user1\', \'user2\'];

For this object I would like to create a list of span li

相关标签:
3条回答
  • 2021-01-21 09:40

    Assuming users should contain strings only, try this:

    var users = ['user1', 'user2'];
    for (var i = 0; i < users.length; i++) {
        $("<span />").text(users[i]).appendTo("body");
    };
    

    Example fiddle

    0 讨论(0)
  • 2021-01-21 09:45

    This would work:

    var users = ['user1', 'user2'];
    
    $.each(users, function() {
        $("<span>", { text : this }).appendTo("body");
    });
    
    0 讨论(0)
  • 2021-01-21 09:47

    You also can use the Array.map method:

    ['user1', 'user2'].map(
        function(a){
            $('<span/>').html(a).appendTo($('body')); return a;
        }
    );
    

    Or even shorter:

    $(['user1','user2'].map(function(a){return '<span>'+a+'</span>'}).join(''))
     .appendTo('body');
    

    Or even Array.filter ;)

    ['user1', 'user2'].filter(
        function(a){
            $('<span/>').html(a).appendTo($('body')); return true;
        }
    );
    

    Or jQuery.each on a jQuery object derived from the Array

    $(['user1', 'user2']).each(
        function(i,a){
            $('<span/>').html(a).appendTo($('body')); return true;
        }
    );
    
    0 讨论(0)
提交回复
热议问题