2016-07-23 71 views
0

你好,我知道關於「on」的方法,這裏的大部分關於「on」的答案都不是特定的。有人可以幫我解決這個問題嗎?如何讓jquery腳本在Ajax dom追加後工作?

$(function(){ 

var pagePositon = 0, 
    sectionsSeclector = 'article#sector', 
    $scrollItems = $(sectionsSeclector), 
    offsetTolorence = 30, 
    pageMaxPosition = $scrollItems.length - 1; 

//Map the sections: 

$scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); }); 

// Bind to scroll 
$(window).bind('scroll',upPos); 

//Move on click: 
$(document).keypress(function(e) { 
    if (e.which == 100 && pagePositon+1 <= pageMaxPosition) { 
     pagePositon++; 
     $('html, body').stop().animate({ 
       scrollTop: $scrollItems.eq(pagePositon).offset().top 
     }, 300); 
    } 
    if (e.which == 97 && pagePositon-1 >= 0) { 
     pagePositon--; 
     $('html, body').stop().animate({ 
       scrollTop: $scrollItems.eq(pagePositon).offset().top 
      }, 300); 
     return false; 
    } 
}); 

//Update position func: 
function upPos(){ 
    var fromTop = $(this).scrollTop(); 
    var $cur = null; 
    $scrollItems.each(function(index,ele){ 
     if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele); 
    }); 
    if ($cur != null && pagePositon != $cur.data('pos')) { 
     pagePositon = $cur.data('pos'); 
    }     
} 
}); 

當你按下「d」或「a」它會轉到next或prev id =「sector」,那很好。但偶爾,在Ajax Call和新文章追加後,腳本無法移動到它們。我知道他們沒有綁定(在刷新dom後)以及如何在Ajax dom更改後使腳本生效?

+1

_it轉到下一個或prev與id =「扇區」_ds必須是**唯一的** – Andreas

+0

您必須更新'$ scrollItems'。否則,它只包含分配時出現的元素。 – Andreas

+0

我知道它,所以我需要一個明顯的例子,夥計們。我甚至不能谷歌的例子來解決我的問題。 – MonkeyCoder

回答

0

解決:

$(function(){ 

var pagePositon = 0, 
    sectionsSeclector = 'article#sector', 
    $scrollItems = $(sectionsSeclector), 
    offsetTolorence = 30, 
    pageMaxPosition = $scrollItems.length - 1; 

//Map the sections: 


// Bind to scroll 


//Move on click: 
$(document).on('keypress', function(e) { 
    $scrollItems = $(sectionsSeclector); 
    pageMaxPosition = $scrollItems.length - 1; 
    $scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); }); 

    $(window).bind('scroll',upPos); 

    if (e.which == 100 && pagePositon+1 <= pageMaxPosition) { 
     pagePositon++; 
     $('html, body').stop().animate({ 
       scrollTop: $scrollItems.eq(pagePositon).offset().top 
     }, 300); 
    } 
    if (e.which == 97 && pagePositon-1 >= 0) { 
     pagePositon--; 
     $('html, body').stop().animate({ 
       scrollTop: $scrollItems.eq(pagePositon).offset().top 
      }, 300); 
     return false; 
    } 
}); 

//Update position func: 
function upPos(){ 
    var fromTop = $(this).scrollTop(); 
    var $cur = null; 
    $scrollItems.each(function(index,ele){ 
     if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele); 
    }); 
    if ($cur != null && pagePositon != $cur.data('pos')) { 
     pagePositon = $cur.data('pos'); 
    }     
} 

});