jQuery动态生成HTML时如何实现每个.row.list容器放8个元素后新建块
修改后的JS代码
function getAllRecipes(){ $.ajax({ type: "GET", url: "https://api.npoint.io/7493fda05b8038212eed", beforeSend: function() { $("#AllRecipe").html('Fetching...') }, success: function(json) { $("#AllRecipe").html('') if(!json.hasOwnProperty('error')){ var add_html = ''; var count_page = 1; // 提前初始化计数器,避免循环内重复声明导致逻辑混乱 var count = 0; // 预先打开第一个分页容器 add_html += '<div id="'+count_page+'" class="row list disable-text-selection pagination_cont active">'; $(json).each(function (new_i, new_val) { if(new_val.calorique == 1){ var sport_recipe = '<span class="badge badge-pill badge-theme-1 position-absolute badge-top-left">SPORT</span>'; }else{ var sport_recipe = ''; } var total_time = new_val.recipe_time + new_val.recipe_time_cooking; // 满8个元素时关闭上一个容器,创建新容器 if(count == 8){ add_html += '</div>'; count_page = count_page + 1; var activeClass = count_page == 1 ? 'active' : ''; add_html += '<div id="'+count_page+'" class="row list disable-text-selection pagination_cont '+activeClass+'">'; count = 0; } // 插入当前卡片元素 add_html += '<div class="col-xl-3 col-lg-4 col-12 col-sm-6 mb-4"><div class="card"><div class="position-relative"><a href="/recipes_details.php?recipeid='+new_val.id+'"><img class="card-img-top" src="'+new_val.image+'" alt=""></a>'+sport_recipe+'</div><div class="card-body"><div class="row"><div class="col-10"><a href="/recipes_details.php?recipeid='+new_val.id+'"><p class="list-item-heading mb-4 pt-1 first_uppercase">'+new_val.name+'</p></a><footer><p class="text-muted text-small mb-0 font-weight-light"><span style="margin-left: 2em" class="inline-flex"><svg style="width: 20px; height: auto" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><span class="ml-1">'+total_time+' min</span></span></p></footer></div></div></div></div></div>' count = count + 1; }); // 循环结束后闭合最后一个分页容器,避免标签不完整 add_html += '</div>'; $("#AllRecipe").html(add_html) } } }); } $( document ).ready(function() { getAllRecipes(); });
核心改动说明
- 修正了分页容器的创建逻辑:循环开始前先打开第一个容器,计数器累计到8的时候自动关闭上一个容器、创建新容器,避免容器过早关闭导致元素外溢
- 移除了原来错误的
new_i % 8 == 2、new_i == 0的关闭容器判断,避免标签嵌套错位 - 循环结束后统一闭合最后一个未收尾的容器,避免出现未闭合的DOM标签
- 计数器
count提前全局初始化,避免循环内重复声明导致计数逻辑混乱
内容的提问来源于stack exchange,提问作者executable
相关产品推荐
相关产品推荐

