2015-09-04 95 views
0

我在純JS中找到了一段代碼來在文本中應用省略號。對同一類的每個元素運行jQuery返回undefined

function dotify(element) { 
    var limit = element.offsetTop + element.offsetHeight; 
    var dots = document.createElement('span'); 
    if (element['data-inner']) 
     element.innerHTML = element['data-inner']; 
    else 
     element['data-inner'] = element.innerHTML; 
    dots.appendChild(document.createTextNode('...')); 
    element.style.overflow = 'hidden'; 
    element.appendChild(dots); 
    while (dots.offsetTop + dots.offsetHeight > limit) { 
     dots.previousSibling.data = dots.previousSibling.data 
      .replace(/\W*\w+\W*$/, '') 
    } 
} 

當我將這段代碼應用到一個元素上時,它就像一個魅力一樣。但是,當我使用each()函數將它應用於具有相同類的每個元素時,我有一個未定義的錯誤。

jQuery(".product-description").each(function() { 
    dotify(jQuery(this)); 
    onresize = function(){ setTimeout(function() { dotify(jQuery(this)); }, 100); }; 
}); 

以下工作:

test = jQuery(".product-description")[0] 
dotify(test); 
onresize = function(){ setTimeout(function() { dotify(test); } 

回答

2

您需要DOM元素引用傳遞到dotify,而不是一個jQuery對象引用。

jQuery(".product-description").each(function() { 
    var el = this; 
    dotify(el); 
    onresize = function() { 
     setTimeout(function() { 
      dotify(el); 
     }, 100); 
    }; 
}); 

注:不知道什麼是onresize功能的代碼

+0

事實是,我也不確定。但是,您的代碼現在可以運行。謝謝。我還有一個與代碼有關的問題,但我應該打開一個新的問題。 – Tasos

+0

@Tasos最好問一個新問題 –

1

donotify方法接受DOM對象,你已經在每個函數傳入jQuery對象。 (即this)使在每個功能的當前上下文的DOM對象將解決該問題:

jQuery(".product-description").each(function() { 
    var current_descr = this; 
    dotify(current_descr); 
    onresize = function(){ setTimeout(function() { dotify(current_descr); }, 100); }; 
}); 
+0

同樣的目的,只是爲了添加,'的jQuery(「產品說明」)[0]'給DOM節點,而不是'jQuery'對象,這就是代碼工作的原因。 – sabithpocker

+0

它適用於這種情況。 –