使用jQuery动态地将用户添加到页面上

时间:2017-10-08 10:39:25

标签: javascript jquery html

我试图使用jQuery动态地将用户添加到页面上,每个用户都必须以某种方式设置样式,不确定我做错了什么......



var user = [
{
  avatar: "http://static2.businessinsider.com/image/5899ffcf6e09a897008b5c04-1200/.jpg",
  username: "Alex",
  position: "dev",
  active: "active",
  lastLogin: 2017
}
];

function addUser(index, user) {
    var avatar = user.avatar;
    var username = user.username;
    var position = user.position;
    var active = user.active;
    var lastLogin = user.lastLogin;

    var $user = 
        "<div class='col-sm-3'>" +
        "<img class='img-circle avatar' style='width: 120px" +    
        "src='" + 
        avatar + "'" +  "/>" + 
        "<h4 style='margin-bottom: -10px;'>" + username + "</h4>" +
        "<h5 style='margin-bottom: -10px;'>" + position + "</h5>" +
        "<h5 style='margin-bottom: -7px;'>" + active + "</h5>"+
        "<h5 style='margin-bottom: -7px;'>" + lastLogin + "</h5>" +
        "<button style='margin-top: 20px'>Edit</button>" +
        "</div>"

    $("#col-centered").append($user);
}

$.each(user, addUser);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="col-centered" class="container-fluid row">

</div>
&#13;
&#13;
&#13;

任何帮助将不胜感激!!

1 个答案:

答案 0 :(得分:0)

如果问题与未显示的img相关,则您错过了关闭style - img

style='width: 120px"属性

var user = [
{
   avatar: "http://static2.businessinsider.com/image/5899ffcf6e09a897008b5c04-1200/.jpg",
   username: "Alex",
   position: "dev",
   active: "active",
   lastLogin: 2017
}];

function addUser(index, user) {
    var avatar = user.avatar;
    var username = user.username;
    var position = user.position;
    var active = user.active;
    var lastLogin = user.lastLogin;

    var $user = 
        "<div class='col-sm-3'>" +
        "<img class='img-circle avatar' style='width: 120px'" +    
        "src='" + 
        avatar + "'" +  "/>" + 
        "<h4 style='margin-bottom: -10px;'>" + username + "</h4>" +
        "<h5 style='margin-bottom: -10px;'>" + position + "</h5>" +
        "<h5 style='margin-bottom: -7px;'>" + active + "</h5>"+
        "<h5 style='margin-bottom: -7px;'>" + lastLogin + "</h5>" +
        "<button style='margin-top: 20px'>Edit</button>" +
        "</div>"

    $("#col-centered").append($user);
}

$.each(user, addUser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="col-centered" class="container-fluid row">

</div>