我是jquery的新手,並在我的主頁上運行腳本來確定容器中的行數(即div)。如果行數超過3或4行(取決於div類是「threeline」還是「fourline」),它將截斷它並添加省略號。然而,這個腳本永遠執行,所以我想知道爲什麼或如何優化。我試圖把我的頭繞在javascript/jquery上,但它對我來說確實是一門外語!爲什麼jquery腳本永遠持續?
有人可以看看這個腳本,讓我知道如何編輯它,使其更快?是否不必要地檢查頁面上的所有元素?
下面是它怎麼叫我的PHP頁面:
<div class="bubble left">
<div class="rounded">
<blockquote class="ellipsis fourline">
<h3><a href="http://www.xyz.com">This is the title</a></h3>
<p>This is the body of the quote; if the body plus title is more than fourlines, then the text will be truncated and an ellipsis will be added</p>
</blockquote>
</div>
<cite class="rounded">March 18, 2010</cite>
</div>
<script type="text/javascript" src="/scripts/js/jquery.ellipsis.js"></script>
<script type="text/javascript"> $(".ellipsis").ellipsis(); </script>
這是jquery.ellipsis.js文件:
(function($) {
$.fn.ellipsis = function()
{
return this.each(function()
{
var el = $(this);
if(el.css("overflow") == "hidden" && el.hasClass('fourline'))
{
var text = el.html();
var fourline = el.hasClass('fourline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(fourline ? el.width() : 'auto')
.height(fourline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = fourline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "…");
}
el.html(t.html());
t.remove();
} else if (el.css("overflow") == "hidden" && el.hasClass('threeline'))
{
var text = el.html();
var threeline = el.hasClass('threeline');
var t = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(threeline ? el.width() : 'auto')
.height(threeline ? 'auto' : el.height())
;
el.after(t);
function height() { return t.height() > el.height(); };
function width() { return t.width() > el.width(); };
var func = threeline ? height : width;
while (text.length > 0 && func())
{
text = text.substr(0, text.length - 1);
t.html(text + "…");
}
el.html(t.html());
t.remove();
}
});
};
})(jQuery);
在此先感謝,我喜歡這個網站!
設置firebug並啓用控制檯和分析器,但是當我重新加載頁面時,什麼都不顯示。在我的代碼中添加了console.profile()和console.profileEnd(),但我仍然沒有收到任何信息。是否因爲我處於開發環境而螢火蟲正在檢查我的主頁的實時版本? – user437157 2010-09-01 17:19:35
我甚至不認爲你需要插入任何代碼。加載您的頁面,打開控制檯,啓用「Persist」按鈕,單擊配置文件。 Profiler正在運行。再次加載您的頁面。再次點擊配置文件將其關閉。你現在應該看到結果。 – 2010-09-01 17:52:56
是的,它只會分析瀏覽器頁面上的代碼,所以你必須確保瀏覽器正在加載腳本的當前副本。您可能希望將firebug與firefox的Web開發人員工具欄結合使用,並通過緩存選項禁用瀏覽器緩存,以確保您始終處理實時頁面/數據。 – 2010-09-01 17:54:23