使用jquery-each函数循环项并将项包装到div容器中



我的Html

<div class="loop">
<article>1<article>
<article>2<article>
<article>3<article>
<article>4<article>
<article>5<article>
<article>6<article>
</div>

我的JS:

$('.loop').find('article').each(function (index, section) {
if ( index < 3) {

// code here 
}
})

我不知道如何解决这个问题:

我想迭代这些项目,并用div包装项目1,2,3。还有项目4,5,6和7,8,9(如果有更多项目(

我想要的Html是:

<div class="loop">
<div="newContainer">
<article>1<article>
<article>2<article>
<article>3<article>
</div>
<div="newContainer">
<article>4<article>
<article>5<article>
<article>6<article>
</div>
</div>

我为您编写了一个解决方案:

$('.loop').find('article').each(function (index, section) {
if(index % 3 ===0)
{
$('.loop').append($('<div>'));
}
$('.loop').children(`div:nth-of-type(${Math.floor(index/3)+1})`).first().append(section);
})

以下是一个完整的示例:https://jsfiddle.net/t40ujrbs/

另一种方法是在each中使用wrapAll

var article = $('article');
$.each(article, function (index, section) {
if (index % 3 === 0) {
$(article).slice(index, index + 3).wrapAll("<div class='new-div'>Test text</div>");
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="loop">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
<article>5</article>
<article>6</article>
</div>

如果您喜欢一个更长但更易于理解的解决方案,您可以这样做。

$(document).ready(()=>{
let newDiv = $("<div>");
let generalId=1, ctrl=3;
let dv = $("<div>");
dv.attr("id", "new-container"+generalId);
let oldDiv=$(".loop");
oldDiv.find("article").each(function (index, article) {
ctrl--;
dv.append(article);
if(ctrl==0) {// if ctrl==0, we will append to new main div
newDiv.append(dv);
generalId++;
dv = $("<div>");
dv.attr("id", "new-container"+generalId);
ctrl=3;
}
});
if(ctrl>0) newDiv.append(dv);
oldDiv.html(newDiv.html());
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
</head>
<body>
<div class="loop">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
<article>5</article>
<article>6</article>
<article>7</article>
</div>
</body>
</html>

相关内容

  • 没有找到相关文章

最新更新