我需要在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
答案 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>
标记。