2013-02-07 126 views
0

下面是一段代碼片段。我試圖根據窗口和位置的大小來影響類屬性margin-bottom。我已經得到了這個在所有高度,寬度等實例中的工作......但由於某種原因,所有類都採用了我的最後一個javascript函數的大小。我不確定這是否合理?下面的代碼: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> 

基本上,我李將在後者的JavaScript函數,而不是一個具體的類實例被發現的。所以.t16應該有一個(比如說)14的底部邊界,而.t8應該是42 ...他們都是42.如果我移動它們的順序它們都是14.

想法?

回答

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().循環中

+0

感謝您的答覆。這工作。我已經盯住了這一段時間......感謝那雙新鮮的眼睛。 – theShadraq

+0

感謝您的幫助。 – theShadraq

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'); 
}); 

UPDATE

矮一點:

$("#Full .t16").css('margin-bottom', '1.25em'); 
$("#Full .t8").css('margin-bottom', '4.4175em'); 
+0

Flauwekeul,感謝你的iput。這很好。欣賞它。 – theShadraq

相關問題