[英]Create new list after every second element while iterating over an array in jQuery
在遍历数组以创建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>")
);
}
);
您可以尝试如下操作:
我也不确定,但是我想在循环中添加元素不是很好。 您可以创建整个列表并执行批量操作。
JSFiddle 。
// 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);
您可以使用%运算符(模数(除法余数))以便仅在每个其他迭代中使用代码。
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>")
);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.