我如何在ul标签下拥有所有li标签?

时间:2014-08-18 11:24:00

标签: jquery

我将此作为来自服务器的响应

{
    "vendors": {
        "T1": [
            {
                "name": "Raj Cool Drinks",
                "leaf": [
                    {
                      "toppings": [
                         {
                           "name": "Quantity      1",
                           "value": [
                               "Honey with Chocolate Sauce  10 ML",
                               "Honey with Carmel  10 ML"
                               ]
                         }
                      ]
                    }
                ]
            }
        ]
    }
}

for (var l = 0; l < toppins.length; l++) {
    var toppul = '<ul>';
    $.each(toppins[l].value, function (i, text) {
        if (text != '' && text != undefined) {
            toppul += "<li>" + text + "</li>";
        }
        toppul += "</ul>";
    });
}

使用上面的代码,输出就是这样形成的

<div class="crust-topping-detailsWrap">
    <h5>Item 1</h5>
    <h6>Toppings</h6>
    <ul>
         <li>Honey with Chocolate Sauce  10 ML</li>
    </ul>
    <li>Honey with Carmel  10 ML</li>

屏幕看起来像这样

enter image description here

我怎样才能拥有ul ??

下的所有文字

这样输出看起来像这样

  <ul>
      <li>Honey with Chocolate Sauce  10 ML</li>
      <li>Honey with Carmel  10 ML</li>

  </ul>

4 个答案:

答案 0 :(得分:2)

将以下语句移到.each循环

之外
toppul += "</ul>"; 

$.each(toppins[l].value, function(i, text) {
   if(text!=''&&text!=undefined)
   { 
      toppul += "<li>" + text + "</li>";
   }     
});

toppul += "</ul>"; // Out side .each loop

答案 1 :(得分:1)

您只需更改"</ul>"

的位置即可
for(var l=0;l<toppins.length;l++)
    {
    var toppul = '<ul>';
    $.each(toppins[l].value, function(i, text) {
    if(text!=''&&text!=undefined)
    { 
        toppul += "<li>" + text + "</li>";
    }
    });
     toppul += "</ul>";
    }

您已在<ul>循环

中包含<li>标记的结尾处

答案 2 :(得分:1)

for(var l=0;l<toppins.length;l++)
{
var toppul = '<ul>';
$.each(toppins[l].value, function(i, text) {
if(text!=''&&text!=undefined)
{ 
    toppul += "<li>" + text + "</li>";
}
 toppul += "</ul>";
});
}

更改为

for(var l=0;l<toppins.length;l++)
{
var toppul = '<ul>';
$.each(toppins[l].value, function(i, text) {
if(text!=''&&text!=undefined)
{ 
    toppul += "<li>" + text + "</li>";
}
});
 toppul += "</ul>";
}

甚至

var toppul = '<ul>';
for(var l=0;l<toppins.length;l++)
    {
    $.each(toppins[l].value, function(i, text) {
    if(text!=''&&text!=undefined)
    { 
        toppul += "<li>" + text + "</li>";
    }
    });
    }
toppul += "</ul>";

答案 3 :(得分:0)

试试这个

    for(var l=0;l<toppins.length;l++)
    {
        var toppul = '<ul>';
        $.each(toppins[l].value, function(i, text) {
            if(text!=''&&text!=undefined)
            { 
                toppul += "<li>" + text + "</li>";
            }
        });
        toppul += "</ul>";// Shifted this line.
    }

在内部for循环后附加</ul>