2011-03-18 112 views
4

我有這個簡單的jQuery代碼。單擊它可以獲取標籤的URL,將該頁面加載到當前內容旁邊,將其滑動並移除舊內容。 頁面的狀態與之前完全相同,相同的元素沒有額外的類或樣式。 問題是下一個Ajax調用不起作用。也許我需要.unbind()的東西?jquery ajax請點擊,只能工作一次

我是新來的jquery和JavaScript,所以我很迷茫。非常感謝您的幫助:)

<script type="text/javascript"> 
    $(document).ready(function(){ 
     loadPage(); 
    }); 
    function loadPage(url) { 
     if (url == undefined) { 
      $('body').load('index.html header:first,#content,footer', hijackLinks); 
     } else { 
      $.get(url , function(data) { 
       $('body').append(data); 
       $('body>meta').remove(); 
       $('body>link').remove(); 
       $('body>title').remove(); 
       $('body').append(direction); 
       sm = $(window).width(); 
       if(direction == "leftnav"){ 
        $('body>header:last,body>#content:last,footer:last').css("left", "-" + sm + "px"); 
        footerheight = $('body>#content:last').outerHeight(false) + $('body>header:last').outerHeight(true) ; 
        $('footer:last').css("top", footerheight); 
        $('body>header,body>#content,footer').css("-webkit-transition-duration","0.5s") 
        $('body>header,body>#content,footer').css("-webkit-transform","translate(" + sm + "px,0px)"); 
       }; 
       if(direction != "leftnav"){ 
        $('body>header:last,body>#content:last,footer:last').css("left", sm + "px"); 
        footerheight = $('body>#content:last').outerHeight(false) + $('body>header:last').outerHeight(true) ; 
        $('footer:last').css("top", footerheight); 
        $('body>header,body>#content,footer').css("-webkit-transition-duration","0.5s") 
        $('body>header,body>#content,footer').css("-webkit-transform","translate(-" + sm + "px,0px)"); 
       }; 
       setTimeout(function(){ 
        $('body>header:not(:last),body>footer:not(:last),body>#content:not(:last)').remove() 
       },500); 
       setTimeout(function() { 
        $('body>header,body>footer,body>#content').removeAttr('style') 
       },500); 
      }); 
     } 
    } 
    function hijackLinks() { 
     $('a').click(function(e){ 
      e.preventDefault(); 
      loadPage(e.target.href); 
     direction = $(this).attr('class'); 
     }); 
    } 
</script> 

回答

17

由於要裝載正在取代你的body事件處理程序是最有可能不會保持內容的內容dynmically。

要解決這個問題,你需要調整你的點擊處理程序爲使用live()delegate()

$('a').live("click", function(e){ 
    e.preventDefault(); 
    loadPage(e.target.href); 
    direction = $(this).attr('class'); 

}); 
+0

謝謝。令人驚訝的是,我看着生活,但我沒有得到它的工作strangly。這是awsome :) 再次感謝 – cmplieger 2011-03-18 01:59:40

+0

沒問題,很高興我可以幫忙。 – 2011-03-18 02:01:17

8

的人「在」閱讀後2013年做的,現在「活」現在已經貶值的新途徑(例如wordpress分頁):

/*******ajax pagination*******/ 
jQuery(document).on('click', '#pagination a', function(e){ 
    e.preventDefault(); 
    var link = jQuery(this).attr('href'); 
    jQuery('#content').html('Loading...'); //the 'main' div is inside the 'content' div 
    jQuery('#content').load(link+' #main'); 
}); 

.live()函數已折舊,所以請使用.on()代替。顯然也需要jQuery庫。