如何在JavaScript中实现每行含3个col-md-4动态元素的布局
解决Ajax动态生成每行最多3个col-md-4元素的问题
我来帮你调整这段代码,让它实现每行最多包含3个col-md-4的需求,同时修正原代码里的小拼写错误~
修改后的完整代码
$.ajax({ url: '../php/admin/upcoming_match.php', type: 'post', data: {}, success: function(response) { var data = JSON.parse(response); if (data !== '') { var parent = document.getElementsByClassName('carousel')[0]; var currentRow = null; var colCount = 0; // 记录当前行已添加的col数量 $.each(data, function(i, item) { // 当当前行不存在,或者当前行已经有3个col时,创建新的row if (!currentRow || colCount === 3) { currentRow = document.createElement("div"); currentRow.setAttribute("class", "row"); currentRow.setAttribute("id", "row" + Math.floor(i/3 + 1)); // 按行号命名row parent.appendChild(currentRow); colCount = 0; // 重置col计数器 } // 创建col-md-4元素 var col = document.createElement("div"); col.setAttribute("class", "col-md-4"); col.setAttribute("id", item.id); // 直接用item.id更简洁 currentRow.appendChild(col); colCount++; }); } } });
关键调整说明
- 移除了原代码中每次循环都创建row的逻辑:改为判断当前行是否已满(3个col)或未初始化时才创建新row
- 添加了
colCount计数器:用来追踪当前行已添加的列数,满3个就触发新row创建 - 修正了拼写错误:原代码里的
getElementbyId改为正确的getElementById(不过修改后的代码里已经不需要这个方法了,直接操作currentRow更高效) - 优化了row的ID命名:用
Math.floor(i/3 + 1)生成连续的行号,比如第1-3条数据对应row1,第4-6条对应row2,以此类推
这样处理后,不管你获取到多少条数据,都会自动按每行最多3个col的规则生成对应的row结构啦~
内容的提问来源于stack exchange,提问作者user11714510
相关产品推荐
相关产品推荐

