在遍历对象后添加主题中断

Adding thematic break after iterating through an object

我正在使用 $.each 遍历一个对象,并且我正在努力在每 7 个之后添加一个主题休息 property:value。

$.each(element, function (key, value) {
  $("#result1").append(key + ": " + value + "<br>");
});

我正在使用上面的代码,我能够在浏览器的新行上显示每个 property:value,但就是不知道如何添加主题中断。有可能吗?

欢迎提出任何建议。

您需要跟踪索引,或者像我这里那样实现一个计数器,并使用模数(余数)运算符 % 在您想要的间隔上插入一个中断。

The remainder operator (%) returns the remainder left over when one operand is divided by a second operand.

const element = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'};

let i = 0;
$.each(element, function (key, value) {
  if (i%7 === 0) $("#result1").append("<hr />");
  
  $("#result1").append(key + ": " + value +"<br>");
  
  i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="result1"></div>

或者使用纯 js...

const element = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight'};

let result = document.getElementById('result1');

Object.entries(element).forEach(([key, value], i) => {
  if (i%7 === 0) result.innerHTML += '<hr />';
 
  result.innerHTML += `${key}: ${value} <br>`;
});
<div id="result1"></div>