您的位置:首页 > Web前端 > JQuery

Load Content While Scrolling With jQuery and MVC 3.0

2011-10-29 16:30 447 查看
Source:http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/ <---
http://webdeveloperplus.com/jquery/create-a-dynamic-scrolling-content-box-using-ajax/
http://superdit.com/2011/04/07/jquery-collapsible-load-scroll/

Content structure look like:[/b]
<div class="contentlatest" data-id="8">Some content is here...</div>
<div class="contentlatest" data-id="9">Some content is here...</div>

Firstly,I created a controller like:[/b]

public ActionResult Content()
{
int count = 5;
var list = JokeRepository.FindAll().OrderByDescending(j => j.CreateTime).Take(count);
return View(list);
}
public ActionResult ScrollToContent(int lastId)
{
int count = 5;
var list = JokeRepository.FindAll()
.Where(i => i.Id < lastId)
.Take(count).OrderByDescending(i => i.Id);

return Json(list,JsonRequestBehavior.AllowGet);
}

Then,a view is created.[/b]

@model IEnumerable<Funny.Models.Joke>

@foreach (var item in Model)
{
<div class="contentlatest" data-id="@item.Id">@item.Title</div>
}
<div id="lastpost-loading">
</div>

Finally,let's write some js to achieve scroll to load data.[/b]

<script type="text/javascript">
$(document).ready(function () {
var fetching = false;
var lastPost = function () {
fetching = true;
$('div#lastpost-loading').html('<img src=\'#\'" /Content/images/loading.gif">');
$.post("/Admin/Admin/Scroll?lastId=" + $('.contentlatest:last').data('id'),
function (data) {
if (data) {
for (var i in data) {
$('.contentlatest:last').after($.format('<div class=\"contentlatest\" data-id=\"{0}\">{1}</div>', data[i].Id, data[i].Title));
}
}
setTimeout(function(){
fetching = false;
},300);
$('div#lastpost-loading').empty();
}, "json");
};

$(window).scroll(function () {
var bufferzone = $(window).scrollTop() * 0.20;
if (!fetching && ($(window).scrollTop() + bufferzone > ($(document).height() - $(window).height()))) {
lastPost();
}
else{
$('div#lastpost-loading').text('data loaded');
}
});
});
</script>

Hope this help,
Lisknove.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: