jquery - Django Infinite Scroll 没有运行 Ajax 的东西
问题描述
我已经使用了本教程并在 django 中实现了无限滚动并加载了页面。
但是,我的 Ajax 调用仅在第一页加载中有效,在随后的延迟加载中无效。我已经按照这个答案使用 $items.each.... 代码块。
但使用上述方法后,现在航点不再加载页面,我卡在第一页本身(Ajax 调用正在工作)。删除代码后,延迟加载能够加载后续页面。我正在使用带有 Django 3 的 Bootstrap 4。有什么建议吗?
我正在添加阻止延迟加载的脚本。
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
<script>
$(document).ready(function() {
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function ($items) {
$('.loading').hide();
$items.each(function(){
$(this).find('.like').on('click', likecommentevent);
}
}
});
});
</script>
编辑:备用更新,但这不是我需要的
我尝试了上面 onAfterPageLoad 的替代方法,并且延迟加载有效。但是现在 Ajax 调用被调用了两次或更多。
onAfterPageLoad: function ($items) {
$('.loading').hide();
$('.like').on('click', likecommentevent);
}
解决方案
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
<script>
$(document).ready(function() {
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function ($items) {
$('.loading').hide();
$items.find('.like').on('click', likecommentevent);
}
});
});
</script>
进一步扩展这likecommentevent
是一个存储有函数的值。(我的行话远非专业)它likecommentevent
来自哪里,它存储什么?它可能看起来像这样:这类似于 upvote/downvote 系统。
var likecommentevent = function(event){
var answerid=$(this).data('answer');
// Ajax
$.ajax({
url:"/save-downvote",
type:"post",
data:{
answerid:answerid,
csrfmiddlewaretoken:"{{csrf_token}}"
},
dataType:'json',
success:function(res){
var _prevupvote=$(".downvote-count-"+answerid).text();
if(res.bool==true){
$(".downvote-count-"+answerid).text(parseInt(_prevupvote)+1);
}
}
});
}
无论你有什么功能,以这种方式存储并传入onAfterLoad:function($items){ ##here## }
推荐阅读
- python - 将 DataFrame 写入编码的 JSON 换行符分隔
- c# - 检查电子邮件是否存在,自动重新连接 tcpclient c#
- html - Change in boostrap from one grid size col to another
- python - Qt GUI 内循环?
- linux - netinet/sctp.h:没有这样的文件或目录
- javascript - 获取在一个文件中设置的 chrome 存储值,在另一个文件中
- rust - Rust 中 JavaScript 的 DataView 等价于什么?
- ruby - ruby 正则表达式测试字符串的精确匹配
- javascript - 如何在 PHP 和 AJAX 中使用更新按钮更新任何行,而不仅仅是顶行
- javascript - 如何在日期字段中设置初始值或默认值?