html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>
加载更多
</title>
<style>
ul,li{
margin: 0;
padding: 0
}
#ct li{
text-align: center;
list-style:none;
border: 1px solid #ccc;
padding: 10px;
margin-top: 10px;
cursor:pointer;
}
#load-more{
display: block;
margin: 10px auto;
text-align: center;
cursor: pointer;
}
#load-more img{
width: 40px;
height: 40px;
}
.btn{
display: inline-block;
height: 40px;
line-height: 40px;
width: 80px;
border: 1px solid #E27272;
border-radius: 3px;
text-align: center;
text-decoration: none;
color: #E27272;
}
#ct li.hover{
background:#fed136;
color:#fff;
}
.text{
text-align: center;
}
</style>
</head>
<body>
<ul id="ct">
</ul>
<a id="load-more" class="btn" href="#">
加载更多
</a>
<p class="text"></p>
</body>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>
<script>
var $loadMoreBtn = $('#load-more'),
$ct = $('#ct');
$ct.on('mouseover','li',function(){
$(this).addClass('hover')
});;
$ct.on('mouseout','li',function(){
$(this).removeClass('hover');
});
var pageIndex = 0;
$loadMoreBtn.on('click', function(){
if($(this).data('isLoading')){ //获取一个状态锁
return;
}
$(this).data('isLoading', true) //设置一个状态锁,防止在加载的数据回来之前用户多次点击
.html('![](loading.gif)'); //链式调用,换行也没关系,对齐好看些
$.get('/getNews',{page:pageIndex}).done(function(ret){
pageIndex++;
appendHtml(ret);
$loadMoreBtn.data('isLoading', false)
.text('加载更多'); //链式调用,换行也没关系,对齐好看些
console.log(pageIndex)
}).fail(function(){
$loadMoreBtn.data('isLoading', false)
.text('加载更多'); //链式调用,换行也没关系,对齐好看些
alert('系统异常');
})
});
function appendHtml(news){
console.log(news)
if(news.length === 0){
$('#load-more').remove();
$('.text').text('没有数据了');
return;
}else{
var html = '';
$.each(news, function(){
html = '<li>' + this.title + '</li>'
$('ul').append(html);
})
}
}
</script>
</html>
server-mock模拟后端代码
app.get('/getNews', function(req, res){
var news = [
{
title: '内容1'
},
{
title: '内容2'
},
{
title: '内容3'
},
{
title: '内容4'
},
{
title: '内容5'
},
{
title: '内容6'
},
{
title: '内容7'
},
{
title: '内容8'
}
];
var page = req.query.page;
var length = 2;
var retnews = news.slice(page*length, page*length+length);
setTimeout(function(){
res.send(retnews);
}, 1000)
})
lodaing
动态加载
【个人总结,如有错漏,欢迎指出】
:>
网友评论