结束循环错误地创建HTML

时间:2014-09-08 16:03:24

标签: javascript jquery

我需要在for循环中动态创建这段HTML

<ul class="restListings">
   <br>
   <sub class="sub">Your Favorite Restaurant</sub>
   <li>
      <h6>Restaurant Name</h6>
       <p>Near Office</p>
   </li>
   <li>
      <h6>Restaurant Name</h6>
      <p>Near Office</p>
   </li>
   <li>
      <h6>Restaurant Name</h6>
      <p>Near HDFC Bank, Madhapur, Hyderabad.</p>
   </li>
   <li>
      <h6>Restaurant Name</h6>
      <p>Near Office</p>
   </li>
</ul>

但我最终要创建这个HTML

<ul class="restListings" style="display: block;">
   <sub class="sub">Your Favorite Restaurant<br>
      <li>
      </li>
      <h6>OhrisHome</h6>
      <p>Near Office</p>
      <li>
      </li>
      <h6>SwagtahtHome</h6>
      <p>Near Home</p>
      <li>
      </li>
      <h6>ParadiseHome</h6>
      <p>Secundrabad</p>
   </sub>
</ul>

这是我的代码,它产生了上述

var response =
[
    {
        "RestaurantName": "OhrisHome",
        "Locality": "Near Office"

    },
    {
        "RestaurantName": "SwagtahtHome",
        "Locality": "Near Home"

    },
    {
        "RestaurantName": "ParadiseHome",
        "Locality": "Secundrabad"

    }
];

var divhtml = $('<sub class="sub">Your Favorite Restaurant</sub>');
divhtml.append('<br>');

for(var i=0;i<response.length;i++)
{
divhtml.append('<li>');
divhtml.append('<h6>'+response[i].RestaurantName+'</h6>');
divhtml.append('<p>'+response[i].Locality+'</p>');
divhtml.append('</li>');
}

$('.restListings').append(divhtml);

这是我的jsfiddle

http://jsfiddle.net/eb1t5jop/

1 个答案:

答案 0 :(得分:1)

相反,你这样做:

for(var i=0;i<response.length;i++)
{
    divhtml.append('<li>
        <h6>'+response[i].RestaurantName+'</h6>
        <p>'+response[i].Locality+'</p>
        </li>');
}

或者:

for(var i=0;i<response.length;i++)
{
    theHtml = '<li>';
    theHtml += '<h6>'+response[i].RestaurantName+'</h6>';
    theHtml += '<p>'+response[i].Locality+'</p>';
    divhtml.append(theHTML + '</li>');
}

<sub>中删除<ul>标记。