简体   繁体   English

追加后jquery延迟加载和其他Jquery / javascript函数不起作用

[英]jquery lazy load and other Jquery / javascript functions don't work after append

I'm attempting to create a page where a user can view pictures and like or dislike them. 我正在尝试创建一个页面,用户可以在其中查看图片并喜欢或不喜欢它们。 To make it user friendly, I'm creating a function that when a user clicks "load more post" jquery will fetch data from server.. I used append for this but javascript functions from the appended file don't work(function like lazy load, like and dislike) here is a sample of my code. 为了使其易于使用,我正在创建一个函数,当用户单击“加载更多帖子”时,jquery将从服务器获取数据。.我为此使用了append,但是来自附加文件的javascript函数不起作用(像lazy这样的函数加载(喜欢和不喜欢))是我的代码示例。

<div id='updatepost' class='col-md-12'></div>
<div class='col-md-12'>
<button class='btn btn-default' id='loadmore'>Load more post</button>
</div>

<script>
pages1 = 5;
pages2 = 10;
$("#loadmore").on("click", function(event) {
event.preventDefault();
loadData = 'pages1=' + pages1 + '&pages2=' + pages2;
    $.ajax({
    type: "GET",
    url: "loadpost.php",
    data: loadData,
    cache: false,
    success: function(html) {
    $("div#updatepost").prepend(html);
    }
    });

});
</script>
<script type='text/javascript' src='js/loadpost.js'></script>

and here's the loadpost.php and javascript functionsfor likepost, dislikepost and lazy load don't work anymore.

<img data-original='upload-image/uploads/myiamge.jpg'  class='lazy'>
<span class='likepost'>like</span>
<span class='dislikepost'>dislike</span>

Use a lazy loader, which supports auto-initializing / self-initializing . 使用惰性加载程序,它支持自动初始化/自我初始化

Otherwise you need to recall initialization code after append: 否则,您需要在追加后重新调用初始化代码:

$("div#updatepost").prepend(html).find('img.lazyload').lazyload();

But in case you are using a lot of AJAX, I really suggest to use the lazySizes script linked above. 但是,如果您使用了大量的AJAX,我真的建议您使用上面链接的lazySizes脚本。 The normal jQuery lazyload produces memory leaks on AJAX heavy sites. 普通的jQuery lazyload在AJAX重载站点上产生内存泄漏。

For your like/dislike functionality you can use event delegation: 对于喜欢/不喜欢的功能,可以使用事件委托:

$('#updatepost').on('click, '.likepost', function(){
    //you like code
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM