Ie8慢脚本消息为jquery loop / .each



在ie8中抛出以下消息

"此页上的一个脚本导致Internet explorer运行缓慢"

这发生在改变一个选择框触发以下代码时,我知道用php做这个会更好,但不幸的是,这不是一个选项。

代码显示从下拉菜单中选择的地点传递的事件。当一个地点被选中时,所有不在该地点的事件都被隐藏。

代码运行的页面是http://sussexpast.co.uk.blueplanetdns.com/events

感谢
jQuery(function($) {
    function hideMonths(){
        var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
        for( var i = 0; i < months.length; i++ ){
            //alert(months[i]);
            $('.events-list .post:visible .event-month:contains('+months[i]+')').not(':first').css('visibility','hidden');
        }
    }
    $(document).ready(function(){
        hideMonths();
    });
    $('.event-location-filter select').change( function() {
        var selectedProperty = $(this).val();
        //alert(selectedProperty);
        $('.post').each( function(){
            $(this).show()
            var eventProperty = $(this).find('.venue a').text();
            //alert(eventProperty);
            if( selectedProperty == 'Select a location' ){
                $(this).show()
                hideMonths();
            }
            else{
                if( eventProperty !== selectedProperty ){
                    $(this).hide()
                    $('.events-list .event-month').css('visibility','visible');
                    hideMonths();
                }
            }
        });
    });
});

缓存大部分选择器,以便在每次迭代时不搜索整个dom。

function hideMonths(){
    var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    var $eventMonths = $('.events-list .post:visible .event-month').not(':first');
    for( var i = 0; i < months.length; i++ ){
        //alert(months[i]);
        $eventMonths.filter(':contains('+months[i]+')').css('visibility','hidden');
    }
}

我也认为没有理由为每个帖子都这样做,而是在.each之后做。

    $('.post').each( function(){
        $(this).show()
        var eventProperty = $(this).find('.venue a').text();
        //alert(eventProperty);
        if( selectedProperty == 'Select a location' ){
            $(this).show()
            //hideMonths();
        }
        else{
            if( eventProperty !== selectedProperty ){
                $(this).hide()
                $('.events-list .event-month').css('visibility','visible');
                //hideMonths();
            }
        }
    });
    hideMonths();

最新更新