在 jQuery 中迭代数组时,每隔一个元素创建新列表

Create new list after every second element while iterating over an array in jQuery

本文关键字:元素 一个 jQuery 创建 新列表 列表 数组 迭代      更新时间:2023-09-26

在遍历数组以创建 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);

您可以使用 % 运算符(模数(除法余数))以便仅每隔 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>")
      );
  }
);