Javascript 每 n 次,创建新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18841718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript every nth, create new row
提问by SBB
I have a products page that I want to show 3 items in each row and then if it has more, create a new row and show more. So 3 cols per row with unlimited rows. Below is the code that I have that contains my loop which I assume the code will need to go into.
我有一个产品页面,我想在每行中显示 3 个项目,然后如果有更多项目,则创建一个新行并显示更多项目。所以每行 3 列,行数不受限制。下面是我拥有的包含我的循环的代码,我认为代码需要进入。
$(data).find('products').each(function() {
itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();
items +='<div class="row-fluid">\
<div class="span3">Col 1</div>\
<div class="span3">Col 2</div>\
<div class="span3">Col 3</div>\
</div>';
count++;
});
Here is where I need to do it but I am a little stuck on how to approach this. If the count is dividable by 3 I assume it will then need to create a new row.
这是我需要做的地方,但我对如何解决这个问题有点困惑。如果计数可被 3 整除,我认为它将需要创建一个新行。
Thanks for any help or input you can provide.
感谢您提供的任何帮助或意见。
回答by Itay
First of all, no need to handle a count
variable on your own, the .each()
function already supplies an index element(as an optional argument).
首先,不需要自己处理count
变量,该.each()
函数已经提供了一个索引元素(作为可选参数)。
With the modulus
operator you can get the remainder from dividing the index
by 3. Then you can tell when do you need to print the opening of the row and the ending of it.
使用modulus
运算符,您可以通过将index
3除以得到余数。然后您可以判断何时需要打印行的开头和结尾。
$(data).find('products').each(function(index) {
itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();
if ((index % 3) == 0) items += '<div class="row-fluid">';
items += '<div class="span3">Col 1</div>';
if ((index % 3) == 2) items += '</div>';
});
if (items.substr(-12) != '</div></div>') items += '</div>';
回答by Jon P
Going left field, don't! Use CSS instead.
去左场,不要!改用 CSS。
Style up your span3
class to have a with of 30ish % with a display of inline block. That way when you decide to display 2, 4 or 60 per row you only need to change the CSS. This also opens you up to change the number of items per row with CSS media queries for diferent viewports e.g. mobile.
为您的span3
班级设计风格,使其具有 30ish % 并显示内联块。这样,当您决定每行显示 2、4 或 60 个时,您只需要更改 CSS。这也使您可以使用针对不同视口(例如移动设备)的 CSS 媒体查询更改每行的项目数。
Further more this way you don't need to worry about closing off the row when your items returned aren't divisible by 3
此外,当您返回的项目不能被 3 整除时,您无需担心关闭该行
On a side note, if you decide to go the CSS route, consider using <ul>
and <li>
instead, as semanticaly you have a list.
附带说明一下,如果您决定走 CSS 路线,请考虑使用<ul>
,<li>
而在语义上,您有一个列表。
UpdateFiddle updated to demonstrate use of li
and the flexibility of this approach.
更新Fiddle 更新以演示li
此方法的使用和灵活性。
回答by jphase
You should use modulus: http://msdn.microsoft.com/en-us/library/ie/9f59bza0(v=vs.94).aspxIt gives you a remainder back from dividing two numbers so you could probably do this with something like (inside your .each):
你应该使用模数:http: //msdn.microsoft.com/en-us/library/ie/9f59bza0(v= vs.94).aspx它给你一个除以两个数字的余数,所以你可以用类似于(在您的 .each 中):
if(!($(this).index() % 2)){
// Add your row
}
$(this).index() returns the index of your .each() and the % 2 returns the remainder of that index divided by 2 so the first 3 times this runs it'd be like this:
$(this).index() 返回 .each() 的索引,% 2 返回该索引除以 2 的余数,所以前 3 次运行它会是这样的:
- 0 / 2 = 0 = add a row
- 1 / 2 = .5 = don't add a row
- 2 / 2 = 1 = don't add a row
- 0 / 2 = 0 = 添加一行
- 1 / 2 = .5 = 不添加一行
- 2 / 2 = 1 = 不添加一行
Hopefully this is what you meant.
希望这就是你的意思。
回答by Frambot
Here's what I think is a cleaner approach:
这是我认为更清洁的方法:
// Map each product to a cell.
var cells = $(data).find('products').map(function() {
var itemName = $(this).find('itemName').text();
var itemDesc = $(this).find('itemDesc').text();
var itemID = $(this).find('id').text();
return $('<div></div>').addClass('span3').text(itemName+' '+itemDesc+' '+itemID);
});
// Collect the cells into rows.
var rows = [];
for (var i=0, j=cells.length; i<j; i+=3) {
rows.push(
$('<div></div>')
.addClass('row-fluid')
.append(cells.slice(i,i+3))
);
}
回答by Super Hornet
The best approach to your issue is using jquery template. you can fetch your data in Json format by ajax request and create rows dynamically by jquery template:
解决您的问题的最佳方法是使用 jquery 模板。您可以通过 ajax 请求以 Json 格式获取数据,并通过 jquery 模板动态创建行:
<script src="jquery.tmpl.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var data = [
{ name: "Astor", product: "astor", stocklevel: "10", price: 2.99},
{ name: "Daffodil", product: "daffodil", stocklevel: "12", price: 1.99},
{ name: "Rose", product: "rose", stocklevel: "2", price: 4.99},
{ name: "Peony", product: "peony", stocklevel: "0", price: 1.50},
{ name: "Primula", product: "primula", stocklevel: "1", price: 3.12},
{ name: "Snowdrop", product: "snowdrop", stocklevel: "15", price: 0.99},
];
$('#flowerTmpl').tmpl(data).appendTo('#row1');
});
</script>
<script id="flowerTmpl" type="text/x-jquery-tmpl">
<div class="dcell">
<img src="${product}.png"/>
<label for="${product}">${name}:</label>
<input name="${product}" data-price="${price}" data-stock="${stocklevel}"
value="0" required />
</div>
</script>
Html:
网址:
<div id="row1" class="drow"></div>
回答by Alex Art.
var $products = $(data).find('products');
var num_of_rows = Math.ceil($products.length/3)
//Create your rows here each row should have an id = "row" + it's index
$products.each(function(i,val){
var row_index = Math.ceil(i/3)
$('#row' + row_index).append("<div>Col"+i%3+"</div>")
});
Something like that should work
这样的事情应该工作