如何在jQuery函数文本中添加新行()

时间:2015-01-02 12:48:03

标签: javascript jquery

我想在jQuery函数中插入新行。

$.ajax({ 
        url:"http: //192.168.1.4/Experiements/webservices/api.php", 
        type:"GET", 
        dataType:"json", 
        data:{type:"login", UserName:userId,Password:userPassword}, 
        ContentType:"application/json", 
        success: function(response){                        
        alert(JSON.stringify(response));                                   
              var detailsDiv=$("div#details");
              var userName=response[0].User.UserName;                              
              var ID=response[0].User.Followers;
              var Email=response[0].User.email;
              var Dish=response[0].User.Dish;                              
             detailsDiv.text("UserName: "+userName+"ID: "+ID+"Email: "+Email+"Dish: "+Dish);
         }, 

检查以上代码中的以下行:detailsDiv.text("UserName: "+userName+"ID: "+ID+"Email:"+Email+"Dish: "+Dish); 它提供的输出如下:UserName: Ravi ID: 123 Email:ravi@gmail.com Dish: Indian Dishes

我希望输出

UserName: Ravi  
ID: 123  
Email:ravi@gmail.com  
Dish: Indian Dishes

3 个答案:

答案 0 :(得分:3)

.text更改为.html并使用<br>元素,它会插入换行符:

detailsDiv.html("UserName: "+userName+"<br>ID: "+ID+"<br>Email: "+Email+"<br>Dish: "+Dish);
//                                      ^^            ^^                  ^^

如果您正在撰写XHTML,则必须关闭<br>代码,例如<br />

detailsDiv.html("UserName: "+userName+"<br />ID: //...

答案 1 :(得分:2)

试试这个......

jQuery的:

$.ajax({ 
        url:"http: //192.168.1.4/Experiements/webservices/api.php", 
        type:"GET", 
        dataType:"json", 
        data:{type:"login", UserName:userId,Password:userPassword}, 
        ContentType:"application/json", 
        success: function(response){                        
        alert(JSON.stringify(response));                                   
              var detailsDiv=$("div#details");
              var userName=response[0].User.UserName;                              
              var ID=response[0].User.Followers;
              var Email=response[0].User.email;
              var Dish=response[0].User.Dish;                              
            $("#username").html(userName);
            $("#userid").html(ID);
            $("#email").html(Email);
            $("#dish").html(Dish);
         },
});

HTML:

         <p id="username"></p>
         <p id="userid"></p>
         <p id="email"></p>
         <p id="dish"></p>

答案 2 :(得分:1)

您可以使用p元素和append方法:

detailsDiv.append('<p>UserName: ' + userName + '</p>');
detailsDiv.append('<p>ID: ' + ID + '</p>');
detailsDiv.append('<p>Email: ' + Email + '</p>');
detailsDiv.append('<p>Dish: ' + Dish + '</p>');