[英]Jquery function called from $(document).ready takes too long - IE pops up “stop running script” dialog
我有以下腳本來模仿html中的“ freezepane”功能,例如在excel中,當用戶滾動結果表時,右側和標頭都將滾動。
fnAdjustTable=function(){
var colCount=$('#firstTr>td').length; //get total number of column
var m=0;
var n=0;
var brow='mozilla';
jQuery.each(jQuery.browser, function(i, val) {
if(val==true){
brow=i.toString();
}
});
$('.tableHeader').each(function(i){
if(m<colCount){
if(brow=='mozilla'){
$('#firstTd').css("width",$('.tableFirstCol').innerWidth());//for adjusting first td
$(this).css('width',$('#table_div td:eq('+m+')').innerWidth());//for assigning width to table Header div
}
else if(brow=='msie'){
$('#firstTd').css("width",$('.tableFirstCol').width());
$(this).css('width',$('#table_div td:eq('+m+')').width());//In IE there is difference of 2 px
}
}
m++;
});
$('.tableFirstCol').each(function(i){
if(brow=='mozilla'){
$(this).css('height',$('#table_div td:eq('+colCount*n+')').outerHeight()-1);//for providing height using scrollable table column height
}else if(brow=='msie'){
$(this).css('height',$('#table_div td:eq('+colCount*n+')').innerHeight());
}else{
$(this).css('height',$('#table_div td:eq('+colCount*n+')').height());
}
n++;
});
}
fnScroll=function(){
$('#divHeader').scrollLeft($('#table_div').scrollLeft());
$('#firstcol').scrollTop($('#table_div').scrollTop());
}
問題是,當遍歷“ tableFirstCol” tds時,彈出停止運行腳本的錯誤。 有沒有更有效的方法來做到這一點?
本質上,腳本將調整每個頂部標題和側窗格的大小,以匹配第一行/列的寬度。 如果我以較大的日期范圍(側面標題)運行報表,則通常會在大約30多個側面標題行時彈出腳本。
任何幫助表示贊賞!
您可以為每個列和行生成帶有id
標簽的HTML。 然后只需按名稱進行選擇,而不使用復雜的選擇器。
我會說$('#table_div td:eq('+colCount*n+')')
是一個復雜的選擇器,而$('#row1')
則容易得多。
另外-我相信您正在做的瀏覽器檢查將無法正常工作。 您擁有的代碼會遍歷檢測到的瀏覽器的所有屬性,並將brow
值設置為最后一個。 可以使用$.browser.webkit
類的東西來檢查webkit,使用$.browser.msie
來檢查IE,而不是循環。 就像現在的代碼一樣,我認為您將始終執行else
情況。 有關jQuery瀏覽器對象的更多信息,請參見此處: http : //api.jquery.com/jQuery.browser/
您需要緩存選擇器:
var tableDiv = $('#table_div'),
divHeader = $('#divHeader'),
firstcol = $('#firstcol'),
tableFirstCol = $('.tableFirstCol'),
tds = $('td', tableDiv);
您可以使用列選擇器.eq(n)。
當this.style.height = n
時$(this).css("height", n)
請勿使用$(this).css("height", n)
; 更容易,更快。
這個:
$('.tableHeader').each(function(i){
if(m<colCount){
/* ... */
}
m++;
});
應該:
$('.tableHeader').each(function(i){
if(i<colCount){
/* ... */
}
});
而且我不確定,您甚至需要i<colCount
檢查(但我必須查看HTML)。
瀏覽器嗅探可能沒有必要。 嘗試應用重置樣式表和有效的doctype
或使用HTML5Boilerplate 。
如果您必須瀏覽器嗅探:您可以使用:
if($.browser.mozilla){
/* ... */
}
else if ($.browser.msie){
/* ... */
}
else{
/* ... */
}
您也可以將代碼壓縮很多。 查找DRY原理 。
另外,關於設置tableFirstCol
的高度,您不能只設置行的高度嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.