jQuery问题:无限滚动无法正常运行

时间:2011-09-13 04:27:43

标签: jquery scroll scrollbar

嘿我试图在我的网站上植入这个jQuery插件:http://www.jarlef.com/post/2010/05/25/Infinite-scrolling-with-jQuery.aspx

问题是页面不断加载越来越多的内容,而用户不必向下滚动,这会导致负载缓慢。

jquery代码即时使用:

(function ($) {

    $.fn.infinentScroll = function (settings) {

        // variables
        var isLoading = true;

        // setup default config
        var config = {
            'url': 'gallery.php?page={page}',
            'modifier': '{page}',
            'initialUpdate': 'true',
            'currentPage': '1',
            'setupLoadingPanel': true,
            'loadingPanelID': 'loadingPanel',
            'loadingImage': '',
            'loadingImageAlt': 'Loading more...',
            'loadingMessage': '<b>Loading more...</b>',
            'completeMessage': '<b>No more to show...</b>'
        };

        // merge user provided settings into config object
        if (settings) $.extend(config, settings);


        // check if an update is needed
        var isTimeToUpdate = function () {
            var container = $(element).offset().top + $(element).height() - $(document).height();
            var scroll = $(document).scrollTop();
            return scroll > container;
        };

        // listen to scroll event
        var scrollHandler = function (event) {

            if (!isTimeToUpdate() || isLoading) {
                return;
            }

            config.currentPage++;

            fetchContent();
        };

        var showLoading = function () {
            if (config.loadingPanelID != null) {
                $("#" + config.loadingPanelID).fadeIn();
            }
        }

        var showComplete = function () {
            if (config.loadingPanelID != null && config.completeMessage != null && config.completeMessage.length > 0) {
                $("#" + config.loadingPanelID).hide().empty().append(config.completeMessage).fadeIn().delay(2000).fadeOut();
            }
        }

        var hideLoading = function () {
            if (config.loadingPanelID != null) {
                $("#" + config.loadingPanelID).fadeOut();
            }
        }
        // update content
        var fetchContent = function () {

            isLoading = true;

            // unbind scroll event
            unregisterScrollEvent();

            // show loading message
            showLoading()

            // format url
            var url = config.url.replace(config.modifier, config.currentPage);

            // do request
            $.ajax({
                url: url,
                async: true,
                cache: false,
                success: function (data) { receiveContent(data); }
            });
        };

        // add content to element
        var receiveContent = function (data) {

            hideLoading();

            // if no content is received -> stop listing to the scroll event
            data = jQuery.trim(data);
            if (data.length == 0) {
                showComplete();
                return;
            }

            $(element).append(data);

            isLoading = false;

            // rebind scroll event again
            registerScrollEvent();

            // call more to fill the page
            if (isTimeToUpdate()) {
                config.currentPage++;
                fetchContent();
            }
        };

        var registerScrollEvent = function () {
            $(window).bind("scroll", scrollHandler);
        };
        var unregisterScrollEvent = function () {
            $(window).unbind("scroll", scrollHandler);
        };

        var setupLoadingPanel = function () {
            if (config.loadingPanelID == null) {
                return;
            }
            $(element).after('<div id="' + config.loadingPanelID + '"></div>');
            $("#" + config.loadingPanelID).hide().empty().css('text-align', 'center');

            if (config.loadingImage != null && config.loadingImage.length > 0) {
                var image = new Image();
                image.src = config.loadingImage;
                $("#" + config.loadingPanelID).append('<img src="' + image.src + '" alt="' + config.loadingImageAlt + '" /><br />');
            }

            if (config.loadingMessage != null && config.loadingMessage.length > 0) {
                $("#" + config.loadingPanelID).append(config.loadingMessage);
            }
        };

        // current limitiations -> only allow 1 element
        if (this.length != 1) {
            alert("Only 1 element can be registed");
        }

        var element = this[0];

        if (config.setupLoadingPanel) {
            setupLoadingPanel();
        }

        if (config.initialUpdate) {
            // perform an initial update
            fetchContent();
        }
        else {
            // register scroll events
            registerScrollEvent();
        }

        return this;
    };



})(jQuery);

我的gallery.php:

<?php
include('config/db_con.php');
include('config/config.php');

    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");
    $query = "SELECT COUNT(*) as num FROM `like`";
    $limit = '15';

    /* Setup vars for query. */
    $targetpage = "gallery.php";
    $page = $_GET['page'];
    if ($page > 1)
        $start = 31 + ($limit * $page);                           //if no page var is given, set start to 0

    /* Get data. */                                                             
    $resultst = "SELECT * FROM `like` ORDER BY `count` DESC LIMIT $start,15";
    $new = mysql_query($resultst) or die(mysql_error());

                        while($rows = mysql_fetch_array($new))
                        {    
                                            $like_link1 = htmlspecialchars(html_entity_decode(strip_tags(stripslashes(str_replace('shit', 'sh*t', $rows['like'])))));
                                            $seo_title1 = $like_link1;
                                            $new_like_link = substr($seo_title1,0,500);
                    $new_liketitle = preg_replace("/\n/"," ",$new_like_link);
                    $new_status_like = str_replace('"', '', $new_liketitle);
                    $new_status_like2 = str_replace('&', 'and', $new_status_like);
                    if($rows['imageurl'] == ''){
                        $img_url = 'https://lh3.googleusercontent.com/EU8kFP0MI-ceqGK_YX2E68wq1UdDO7FD26QR0_hwaIT8w4DSp2i5I4YKmi7zzXYKT9PX3flDYqQU6D2UkkdwBdc1VA=s512';
                    }else{ 
                        $img_url = $rows['imageurl'];
                    } ?>
<div class="like" style="padding: 10px 0;" onmouseover="this.className='likehover'" onmouseout="this.className='like'">
    <div style="float:left;padding-left:5px;"></div>
    <div style="float:left;width:620px;">
        <div style="margin:6px 10px 7px 10px;float:left;width:50px;height:50px;border:1px solid #ccc;"><img src="<? echo $img_url; ?>" height="50" width="50" /></div>
        <p style="display:inline block;float:left;width:540px;height:auto;margin:0px;padding:0px;">
            <a style="padding:8px 0 5px 0;" href="<? echo $site;?><? echo $rows['id']; ?>/"><? if(strlen($like_link1) >= '500'){ echo $new_like_link.'...'; }else{ echo $like_link1;} ?></a>
            <span style="float:left;margin-top:8px;display:block;width:500px;">
                <iframe src="http://www.facebook.com/plugins/like.php?href=<? echo $site;?><? echo $rows['id']; ?>&amp;send=false&amp;layout=button_count&amp;width=100&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="float:left;border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"></iframe>
                <a href="http://twitter.com/share" class="twitter-share-button" data-url="<?php echo $site;?><? echo $rows['id']; ?>" data-text="<? echo $new_status_like2; ?>" data-count="horizontal" data-via="iTweetSWAQ">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script><iframe src="http://www.facebook.com/plugins/comments.php?href=<?echo $site;?><? echo $rows['id']; ?>/&permalink=1" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:130px; height:16px;" allowTransparency="true"></iframe>
            </span>
        </p>
    </div>
</div>
                       <?php } ?>

我认为它是jquery代码的问题...
我尝试了什么..任何解决方案?
我的网站 - 出现问题的地方:http://ilikeyoulike.net/

非常感谢你! (:

编辑: 根据要求,这是我的主叫代码:

<div id="output"></div> 
<script type="text/javascript"> 
    <!--
        $(document).ready(new function () {
            $("#output").infinentScroll({ 'url': 'gallery.php?page={page}'  });
        });
    //-->
</script> 

并且可以在ilikeyoulike.net/new-likes找到正确的页面结构。

1 个答案:

答案 0 :(得分:0)

不能直接回答您的问题,但我会改为使用此问题:http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/