0

我正在基于 Twitter Bootstrap 的响应式网格构建一个函数。它.row-fluid用作容器和spans适合行内的节点。每行最多可以有 12 个“跨度”。

我希望我的函数找到任何带有 class 的元素.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>
4

2 回答 2

1

var total = 0, nums = $(this).attr('class').match(/\d+/);

Ugly line - define each var in separate line, because its easier to parse for human beeing ;]

nums = $(this).attr('class').match(/\d+/);

This is string, not a number, do such thing instead:

var numString = $(this).attr('class').match(/\d+/);
var num = parseInt(numString);

Im not sure what happens here:

nums.each(function() {

but nothing good i assume ... each function is for jQuery elements, so maybe jQuery treat your nums as jQuery object

total += this;

Generally inside each parameter function, 'this' keyword is kind of jquery selector, thats why u gets elements instead of numbers

I would say that you need to declare total variable outside spans.each(), because u will get it cleared after each iteration + do sth like that:

total += num;

assuming u will parse numString to number, as i mentioned above.

于 2013-01-22T10:24:14.357 回答
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);
        }
    });
});
于 2013-01-22T10:25:49.083 回答