我有json数据,我已经获取了第一组数据,并将其写入一个ul。我想将剩余的数据分成两个相等的块,并写入另外两个uls。
如何拆分初始索引== 0之后的剩余json?
我的js代码:
$("#storeList").append('<ul class="storeListLeft"></ul>');
$("#storeList").append('<ul class="storeListRight"></ul>');
//run store json data and append to storeList div
var object;
$.getJSON('xml/storeList.json', function(json) {
object = json;
$.each(object.storeList.state, function(index, value) {
var list;
if(index == 0) {
list = $('.storeListLeft');
} else {
list = $('.storeListRight');
}
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).attr('class', 'storeInactive').attr('id', this.storeID).text(this.storeName));
});
list.append(html)
});
}); //end json renderCUrrent输出:
<ul class="storeListLeft">
<li>
<h3>state Name</h3>
<a>store Name</a>
</li>
</ul>
<ul class="storeListRight">
<li>
<h3>state Name</h3>
<a>store Name</a>
<a>store Name</a>
<a>store Name</a>
</li>
<li>
<h3>state Name</h3>
<a>store Name</a>
</li>
</ul>我想要的输出仍然是将第一个项目分配给storeListLeft,然后拆分剩余的数据并将数据块分配给两个单独的uls
所以就像这样:
<ul class="storeList_1"> //which is index == 0
<li>
<h3>state Name</h3>
<a>store Name</a>
</li>
</ul>
<ul class="storeList_2"> //2 & 3 are the split of the remainder after index == 0
<li>
<h3>state Name</h3>
<a>store Name</a>
<a>store Name</a>
<a>store Name</a>
</li>
<li>
<h3>state Name</h3>
<a>store Name</a>
</li>
</ul>
<ul class="storeList_3">
<li>
<h3>state Name</h3>
<a>store Name</a>
<a>store Name</a>
<a>store Name</a>
</li>
<li>
<h3>state Name</h3>
<a>store Name</a>
</li>
</ul>发布于 2011-12-09 23:37:12
在第一个循环之前,将状态分解为您想要的对象:
//get the first state element in the array
var firstStateArray = object.storeList.state.slice(0, 1);
//get the half way point of the states
var mid = Math.round((object.storeList.state.length - 1) / 2);
//assign the first half of the array, starting at the second item (1) to the middle (mid)
var secondStateArray = object.storeList.state.slice(1, mid);
//assign the second half of the array but starting after the first half
var thirdStateArray = object.storeList.state.slice(mid + 1);下面是一个生成标记的函数:
function GenerateMarkup(states, className) {
var html = "<ul class='" + className + "'>";
$.each(states, function () {
html += "<li>";
html += "<h3>" + this.stateName + "</h3>";
$.each(this.store, function (index, value) {
html += "<a href='" + this.storeURL + "' class='storeInactive' id='" + this.storeID + "'>" + this.storeName + "</a>";
});
html += "</li>";
});
html += "</ul>";
$("#storeList").append(html);
}并调用该函数:
//create first list...only one state
GenerateMarkup(firstStateArray, "storeList_1");
//create second list
GenerateMarkup(secondStateArray, "storeList_2");
//create third list
GenerateMarkup(thirdStateArray, "storeList_3");发布于 2011-12-09 04:01:30
你在找模运算符吗?
if(index % 2 == 0) {
list = $('.storeListLeft');
} else {
list = $('.storeListRight');
}偶数索引将返回0,奇数索引将返回1。
https://stackoverflow.com/questions/8436648
复制相似问题