2013-04-09 130 views
0

我已經做了一個簡化的例子(見演示)我正在努力的代碼。我首先有一個函數可以計算<p>在包裝div裏面的行數。根據數字(1,2或3行),包裝div應該得到一個額外的類名稱。如何使這個if語句有效?

這些都是錯誤,我不能工作了:

  • 功能停止(你可以在日誌看)它運行後:

    if (getRows('.item p') === 1) { 
    } 
    
  • 當我登錄該函數的結果我得到的窗口對象,我需要特定的div來添加類,以便我的絕對鏈接可以正確定位

所以結果是絕對連接應該相應地定位到行數。

是的,我知道這段代碼可以寫成不同的形式(就像將絕對鏈接放在我的頁面下面一樣),但它是CMS這樣渲染它,這將是最簡單的解決方法..如果你想要查看應該如何進行的結果,您可以在第一個項目div上添加item_1,在第二個項目上添加item_2等等。

演示:http://jsfiddle.net/pndJx/

if (getRows('.item p') === 1) { 
console.log('1 line'); 
console.log(this); 
} 

if (getRows('.item p') === 2) { 
console.log('2 lines'); 
} 

if (getRows('.item p') === 3) { 
console.log('3 lines'); 
} 

回答

2

您應該使用每個語句:http://jsfiddle.net/astynax777/pndJx/1/

$('.item p').each(function() { 
    var rows = getRows(this); 
    switch (rows) 
    { 
     case 1: 
      console.log('1 line'); 
      break; 
     case 2: 
      console.log('2 lines'); 
      break; 
     case 3: 
      console.log('3 lines'); 
      break; 
    }; 
}); 

function getRows(selector) { 
    var height = $(selector).height(); 
    var font_size = $(selector).css('font-size'); 
    var scale = 1.50 
    var line_height = Math.floor(parseInt(font_size) * scale); 
    var rows = height/line_height; 
    return Math.round(rows); 
} 
+0

不錯,就是我所需要的,可以爲每個案例添加相關的類。非常感謝! – Yunowork 2013-04-09 20:29:21

2

編寫代碼以這種方式

$('.item p').each(function() { 
    var $this = $(this), 
     rows = getRows($this); 

    console.log('%d lines', rows); 

    /* add class */ 
    $this.parent().addClass('item_' + rows); 

}); 

例如小提琴:http://jsfiddle.net/jSevE/

+0

Fabirizio您好,感謝您的提示,可以寫成確實更好,但希望一個簡單的例子來展示。 – Yunowork 2013-04-09 20:30:05

+0

@Yunowork你甚至可以簡化邏輯,將你的類名添加到父分區... se我的更新 – fcalderan 2013-04-10 07:44:40

0

聽起來像是你想要運行的每個單獨<div>這個邏輯。如果是這樣的話,那麼我建議這樣的:

function getRows(selector, context) { 
    var height = $(selector, context).height(); 
    var font_size = $(selector, context).css('font-size'); 
    var scale = 1.50 
    var line_height = Math.floor(parseInt(font_size) * scale); 
    var rows = height/line_height; 
    return Math.round(rows); 
} 

$('div.item').each(function() { 
    if (getRows('.item p', this) === 1) { 
     // if ".item p" equals 1 then add class "item_1" to item div 
     console.log('1 line'); 
     console.log(this); //if i log this i get window (the document), but I need to get the specific div to add the class.. 
    } 

    //console gives back result '1 line' since true and does not continue.. 

    if (getRows('.item p', this) === 2) { 
     // if ".item p" equals 2 then add class "item_1" to item div 
     console.log('2 lines'); 
    } 

    if (getRows('.item p', this) === 3) { 
     // if ".item p" equals 3 then add class "item_1" to item div 
     console.log('3 lines'); 
    } 
}); 

傳遞給.each()this匿名函數的上下文中是指特定<div>元素,而不是window

+0

Afaik並嘗試過,我不能添加一個特定的類到一個行的包裝div? – Yunowork 2013-04-09 20:30:47