我正在构建一个基于Twitter Bootstrap响应网格的功能。它使用.row-fluid
作为容器,spans
作为适合行内的节点。每行最多可以包含12个“跨度”。
我希望我的函数找到类.row-fluid
的任何元素,找到它的子节点,取类名,从中删除“span”(只留一个数字)并将这些数字加在一起。如果结果大于12,我希望它缩小最大数字,直到数字等于12。
听起来很复杂,希望我不是太远了。这是我到目前为止的地方:
$('.row-fluid').each(function() {
var spanned = $(this).children('div[class*=span]').each(function() {
var total = 0, nums = $(this).attr('class').match(/\d+/);
nums.each(function() {
total += this;
}
console.log(total);
}
);
console.log("break");
}
);
目前这是记录整个元素而不仅仅是数字,所以我对于我出错的地方/从这里做什么感到有些不知所措。有什么建议吗?
编辑:结构类似于:
<div class="row-fluid">
<div class="span5">
</div>
<div class="span4">
</div>
<div class="span2">
</div> //Function should check if the 3 above spans <= 12
<div class="row-fluid">
<div class="span8"> //Function should see this and...
<div class="row-fluid">
<div class="span6">Fluid 6</div>
<div class="span6">Fluid 6</div>
</div>
</div>
<div class="span6">Fluid 6</div> //...this and see that they DON'T equal 12, then subtract 2 from the bigger span so that they DO equal 12
</div>
</div>
</div>
答案 0 :(得分:1)
var total = 0, nums = $(this).attr('class').match(/\d+/);
丑陋的行 - 在单独的行中定义每个var,因为它更易于解析人类;]
nums = $(this).attr('class').match(/\d+/);
这是字符串,而不是数字,而是做这样的事情:
var numString = $(this).attr('class').match(/\d+/);
var num = parseInt(numString);
我不确定这里会发生什么:
nums.each(function() {
但我没假设...每个函数都是针对jQuery元素的,所以也许jQuery将你的nums视为jQuery对象
total += this;
通常在每个参数函数中,'this'关键字是一种jquery选择器,这就是为什么你得到元素而不是数字
我想说你需要在spans.each()之外声明一个总变量,因为你会在每次迭代后清除它并执行这样的操作:
total += num;
假设你将numString解析为数字,如上所述。
答案 1 :(得分:1)
我会猜测,这就是你要做的事情:
$('.row-fluid').each(function(i,ele) {
var total = 0;
$(ele).children().each(function(i2, spans) {
if (spans.className.indexOf('span') != -1) {
total += parseInt(spans.className.replace(/[A-Za-z$-]/g, ""),10);
}
});
});