最近给某个客户定制主题时需要实现无限下拉加载功能,以往模板兔都是用某个js插件来实现了,今天教大家一个不用插件实现的方法:
首页,在php里加上相关代码:
<div class="article-list mobantu" id="article-list"> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'caller_get_posts' => 1, 'paged' => $paged ); query_posts($args); while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; wp_reset_query(); ?> </div> <?php $next_page = get_next_posts_link('加载更多'); if($next_page) echo '<div class="article-paging mobantu">'.$next_page.'</div>'; ?>
然后,在js里加上相关代码(前提需要加载了jquery,且网站使用了伪静态分页):
$('.article-paging > a').on('click',function(){ //点击实现加载更多,你可以根据自己需要改成下拉自动加载 var next_url = $(this).attr("href"); var next_text = $(this).text(); if(next_text == '加载更多'){ $(this).text('加载中...'); $.ajax({ type: 'get', url: next_url + '#article-list', success: function(data){ result = $(data).find("#article-list .article-item"); next_link = $(data).find(".article-paging > a").attr("href"); //$(this).attr("href", next_url); if (next_link != undefined){ $('.article-paging > a').attr("href", next_link); $('.article-paging > a').text('加载更多'); }else{ $(".article-paging").remove(); } $(function(){ $("#article-list").append(result.fadeIn(300)); $('.thumb').lazyload({ data_attribute: 'src', placeholder: _BGJ.uri + '/static/img/thumbnail.png', threshold: 400 }); }); $(function() { if (next_url.indexOf("page") < 1) { $("#article-list").html(''); } $("#article-list").append(result.fadeIn(200)); }); } }); } return false; });
搞定!其实这次用这种方式实现无限加载主要是为了另一个高级功能做准备的~~
0 个评论