我正在使用这个AJAX成功函数,使用$ .each方法循环遍历数据,为每个列表创建标题,div和外部ul标记,但我似乎无法弄清楚如何循环创建当我已经循环为列表项创建容器时列出项目。这是我目前正在使用的代码,
$(function() {
var $accordion= $("#accordion");
$.ajax({
type:'GET',
url: "PDOconnect.php",
dataType: "json",
success: function(data){
$.each(data, function(i,data){
$accordion.append('<p>'+ data.name + '</p>');
$accordion.append('<div id='+data.name+'><ul></ul></div>');
});
},
error: function(xhr, textStatus, errorThrown) {
alert( "Request failed: " + textStatus );
}
});// end ajax
});
我理解$.each
已经是一个迭代方法,但如果目标是在迭代中创建另一个迭代怎么办?
你如何在循环中创建一个循环?
说出所需的输出是,
<div id="accordion">
<p> Electrition</p>
<div>
<ul>
<li>jon</li>
<li>jill</li>
</ul>
</div>
<p>Engineer</p>
<div>
<ul>
<li>jerry</li>
<li>laura</li>
</ul>
</div>
</div>
你正从服务器那里得到stdclass对象,
array(
[1] => stdClass Object
(
[id] => 3
[title] => Electrition
[img] =>
[description] =>
[school] =>
[location] => 1
[url] =>
[tablename] => 3
[votes] => 0
[name] => John Doe
[NumJobsdone] => 4
)
[2] => stdClass Object
(
[id] => 2
[title] => Electrition
[img] =>
[description] =>
[school] =>
[location] => 1
[url] =>
[tablename] => 2
[votes] => 0
[name] => Tico Marinez
[NumJobsdone] => 6
)
[3] => stdClass Object
(
[id] => 2
[title] => Engineer
[img] =>
[description] =>
[school] =>
[location] => 1
[url] =>
[tablename] => 2
[votes] => 0
[name] => Jerry Smity
[NumJobsdone] => 6
)
[4] => stdClass Object
(
[id] => 2
[title] => Engineer
[img] =>
[description] =>
[school] =>
[location] => 1
[url] =>
[tablename] => 2
[votes] => 0
[name] => Laura Bastian
[NumJobsdone] => 6
)
)
答案 0 :(得分:1)
您可能正在寻找$.map()
允许您返回指定的数组。
$("#parnet")
.append($.map(data, function(el) {
return $("<div>")
.append(....)
;}
));
这种链接使得jquery如此强大。你可以无限期地以这种方式嵌套循环,它是如何在没有模板的情况下轻松制作表格等