无限滚动 - jQuery不适用于新获取的元素

时间:2014-09-13 09:55:58

标签: jquery infinite-scroll

基本上我正在我的WordPress博客上实现无限滚动(.com),这里是代码:

HTML

<div id="photos" class="display-fix">
    <?php while ( have_posts() ) : the_post(); ?>
    <img src="<?php $url = get_post_thumbnail_id(); $url = wp_get_attachment_image_src($url,'medium'); $url = $url[0]; echo $url; ?>">      
    <?php endwhile; ?>
</div>
<div id="pagination" class="clear right">        
    <?php if(function_exists('wpex_pagination')) { wpex_pagination(); } ?>
</div>

JS

$('#photos').infinitescroll({
    navSelector  : ".next:last", // selector for the paged navigation (it will be hidden) 
    nextSelector : "a.next:last", // selector for the NEXT link (to page 2) 
    itemSelector : "#photos img", // selector for all items you'll retrieve 
    loading: {
        finished: undefined,
        finishedMsg: '',
        img: "<?php echo get_template_directory_uri(); ?>/images/preloader.gif",
        msg: null,
        msgText: '',
        selector: null,
        speed: 'slow',
        start: undefined
    }
});

$('#photos img').hover(function(){
    alert('Works');
});

CSS

#photos {
    width: 100%;
    padding: 20px;
}
#photos img {
    width: 504px;
    margin: 3px;
    float: left;
}
#infscr-loading {
    position: absolute;
    width: 100px;
    height: 100px;
    left: 50%;
    margin-left: -50px;
    bottom: 10px;
}
#infscr-loading img {
    width: 100px;
    height: 100px;
}

当我向下滚动时弹出图像时,悬停警报不起作用,它只适用于显示的第一个图像!弹出的那些不起作用。

有什么理由?我正在使用$(document).ready(function() {我应该使用其他什么吗?

2 个答案:

答案 0 :(得分:0)

这是因为悬停事件附加到最初可见的元素,只需处理infinitescroll的已完成事件:

$('#photos').infinitescroll({
    navSelector  : ".next:last", // selector for the paged navigation (it will be hidden) 
    nextSelector : "a.next:last", // selector for the NEXT link (to page 2) 
    itemSelector : "#photos img", // selector for all items you'll retrieve 
    loading: {
        finished: registerHover,
        finishedMsg: '',
        img: "<?php echo get_template_directory_uri(); ?>/images/preloader.gif",
        msg: null,
        msgText: '',
        selector: null,
        speed: 'slow',
        start: undefined
    }
});

registerHover();

function registerHover()
{
    $('#photos img').hover(function(){
       alert('Works');
    });
}

答案 1 :(得分:0)

您需要使用委托。

变化:

$('#photos img').hover(function(){
    alert('Works');
});

$('#photos img').on('mouseover', function(){
    alert('Works');
});