1

我有以下脚本来模仿 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 行时。

任何帮助表示赞赏!

4

2 回答 2

0

您可以id为每一列和每一行生成带有标签的 HTML。然后只需按名称选择,而不是使用复杂的选择器。

我会说这$('#table_div td:eq('+colCount*n+')')是一个复杂的选择器,但$('#row1')要容易得多。

另外-我相信您为浏览器检查所做的事情将不起作用。您拥有的代码遍历检测到的浏览器的所有属性并将brow值设置为最后一个。而不是你拥有的循环,使用类似$.browser.webkit检查 webkit 和$.browser.msie检查 IE 的东西。正如您现在的代码一样,我认为您将始终执行此else案例。有关 jQuery 浏览器对象的更多信息,请参见此处:http: //api.jquery.com/jQuery.browser/

于 2010-12-29T15:53:28.970 回答
0

你需要缓存你的选择器:

var tableDiv = $('#table_div'),
    divHeader = $('#divHeader'),
    firstcol = $('#firstcol'),
    tableFirstCol = $('.tableFirstCol'),
    tds = $('td', tableDiv);

您可以将 .eq(n) 用于列选择器。

不要使用$(this).css("height", n)when this.style.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你不能只设置行的高度吗?

于 2010-12-29T16:11:18.650 回答