0

下面是一个代码片段。我试图根据窗口的大小和位置来影响类属性margin-bottom 。我已经让它在所有高度,宽度等实例中工作......但由于某种原因,margin-bottom,所有类都采用我的javascript函数中最后一个的大小。我不确定这是否有意义?下面的代码:

//Javascript
var thisMB = null;
$("#Full").find(".t16").each(function () {
                thisMB = '1.25em';
            });
            $("#Full").find(".t8").each(function () {
                thisMB = '4.4175em';
            });

 $(this).css("margin-bottom", thisMB);

<!--html-->
             <div>      
                  <ul class="tlist">
                        <li class="theTeams t16">1 1upLeft upLeft upLeft </li>
                        <li class="theTeams t16">1 1upLeft upLeft upLeft </li>
                        <li class="theTeams t16">3 1 upLeft upLeft upLeft </li>
                        <li class="theTeams t16">4 1 upLeft upLeft upLeft </li>
                        <li class="theTeams t16">5 1 upLeft upLeft upLeft </li>
                        <li class="theTeams t16">6 1 upLeft upLeft upLeft </li>
                    </ul>
                </div>
                <div>
                    <ul class="tlist">
                        <li class="theTeams t8">1 upLeft upLeft upLeft </li>
                        <li class="theTeams t8">3 upLeft upLeft upLeft </li>
                        <li class="theTeams t8">5 upLeft upLeft upLeft </li>
                    </ul>
               </div>

基本上,我的 LI 将采用后一个 javascript 函数,而不是为其找到的特定类实例。所以 .t16 的边距底部应该是(比如说)14,而 .t8 应该是 42 ......它们都是 42。如果我移动订单,它们都是 14。

想法?

4

2 回答 2

2
var thisMB = null;
$("#Full").find(".t16").each(function () {
    thisMB = '1.25em';   <--- this assigns the same variable over and over again
 });
$("#Full").find(".t8").each(function () {
      thisMB = '4.4175em'; <--- so does this
});

$(this).css("margin-bottom", thisMB);   <--- this sets the element to thisMB = the final value.

您一遍又一遍地分配变量,但将其分配给循环外的“this”。如果要设置被选元素的值(this),它需要在each().循环内

于 2013-02-07T17:02:50.270 回答
0

您正在设置一个变量两次,每次都使用不同的值。基本上你正在这样做:

var thisMB = null;
thisMB = '1.25em';
thisMB = '4.4175em';

如果您随后检查 thisMB 的值,您将得到最后一个值集:“4.4175em”。

我认为这就是你想要的:

$("#Full .t16").each(function () {
  $(this).css('margin-bottom', '1.25em');
});

$("#Full .t8").each(function () {
  $(this).css('margin-bottom', '4.4175em');
});

更新

短一点:

$("#Full .t16").css('margin-bottom', '1.25em');
$("#Full .t8").css('margin-bottom', '4.4175em');
于 2013-02-07T17:06:15.153 回答