在迭代数组以创建LI节点时,UL应该在每隔一个LI之后关闭以生成以下HTML结构
所需输出
<ul class="bt-zone-pair">
<li class="bt-zone">
<a href="javascript:void(0)">Team <span>A</span></a>
</li>
<li class="bt-zone">
<a href="javascript:void(0)">Team <span>B</span></a>
</li>
</ul>
<ul class="bt-zone-pair">
<li class="bt-zone">
<a href="javascript:void(0)">Team <span>C</span></a>
</li>
<li class="bt-zone">
<a href="javascript:void(0)">Team <span>D</span></a>
</li>
</ul>
代码小提琴 - https://jsfiddle.net/ylokesh/o8gL3L3o/
的JavaScript
var btTeams = ['Team A', 'Team B', 'Team C', 'Team D', 'Team E', 'Team F', 'Team G', 'Team H'];
var domFragmentTeams = "";
var destinationCol = $('.bt-col1');
// create Teams in column 1
$.each(btTeams, function( intIndex, objValue ){
var listItemWrapper = destinationCol.append(
$('<ul class="bt-zone-pair"></ul>')
);
listItemWrapper.append(
$('<li class="bt-zone"><a href="javscript:void(0)">' + objValue + "</a></li>")
);
}
);
答案 0 :(得分:2)
您可以尝试这样的事情:
我也不确定,但我认为在循环中追加元素并不好。您可以创建整个列表并执行批量操作。
// Define a variable outside so you can append string to it
var _html = "";
$.each(btTeams, function(intIndex, objValue) {
// For odd values, add start tags.
if ((intIndex + 1) % 2 !== 0) {
_html += '<ul class="bt-zone-pair">';
}
// Add li for all cases
_html += '<li class="bt-zone"><a href="javscript:void(0)">' +
objValue + "</a></li>";
// Add end tag for even cases
if ((intIndex + 1) % 2 === 0) {
_html += "</ul>"
}
});
// Append constructed HTML
destinationCol.append(_html);
答案 1 :(得分:1)
您可以使用%运算符(模数(除法余数)),以便仅在每次OTHER迭代时使用代码。
var btTeams = ['Team A', 'Team B', 'Team C', 'Team D', 'Team E', 'Team F', 'Team G', 'Team H'];
var domFragmentTeams = "";
var destinationCol = $('.bt-col1');
// create Teams in column 1
$.each(btTeams, function( intIndex, objValue ){
var listItemWrapper = destinationCol;
if(intIndex%2 ==0) {
destinationCol.append(
$('<ul class="bt-zone-pair"></ul>')
);
}
listItemWrapper.append(
$('<li class="bt-zone"><a href="javscript:void(0)">' + objValue + "</a></li>")
);
}
);