2013-10-03 28 views
0

。那麼,我做的也是pushState腳本,我用jQuery 1.6.2來做,但它使用.live(),但與jQuery的v2.0.3它已棄用。所以,我不知道我怎麼能代替它,看看:再次替換jquery上的.live()

$('.a').live('click', function(e){ 
     history.pushState(null, null, this.href); 
     replacePag(this.href); 
     e.preventDefault(); 
     $(window).bind('popstate', function(){ 
     replacePag(location.pathname); 
    }); 
    }); 

當我用類.A它工作正常,一個元素運行它,但我的網頁有很多.A元素。我用.on()試過,但它都不起作用。

$('.a').on('click', function(e){ 
      history.pushState(null, null, this.href); 
      replacePag(this.href); 
      e.preventDefault(); 
      $(window).bind('popstate', function(){ 
      replacePag(location.pathname); 
     }); 
     }); 

如果你能幫助我,謝謝你的幫助。

好,我的腳本是:

$(function(){ 
    var replacePag = function(ur) { 
     $.ajax({ 
      url: ur, 
      type: 'get', 
      dataType: 'html', 
      success: function(dat){ 
       var domm = $(dat); 
       var titl = domm.filter('title').text(); 
       var htm = domm.filter('#body').html(); 
       $("#body").fadeOut(100, 
       function(){ 
        $(this).html(htm); 
        $('title').text(titl); 
        }).fadeIn(1000); 
      } 
     }); 
    } 

    $('.a').live('click', function(e){ 
     history.pushState(null, null, this.href); 
     replacePag(this.href); 
     e.preventDefault(); 
     $(window).bind('popstate', function(){ 
     replacePag(location.pathname); 
    }); 
    }); 
}); 
+0

此外,你不能只是取代''用一個字.on'字.live',你必須針對當前存在的元素。檢查zeh文檔! – tymeJV

回答

1

on函數允許您在事件「冒泡」到父元素時,通過在另一個元素上處理它們來解決此問題。在這種情況下,我們可以說文檔元素 - 可能有一個更具體的共同父母,你可以選擇。

試試這個:

$(document).on('click','.a', function(e){ 
    history.pushState(null, null, this.href); 
    replacePag(this.href); 
    e.preventDefault(); 
    $(window).bind('popstate', function(){ 
     replacePag(location.pathname); 
    }); 
}); 
+0

謝謝,它的作品也是對的! – Darkness

+0

完美,接受答案,如果你已經解決了你的問題@Darkness –

+0

我有兩個答案說,相同的xD – Darkness

1

像這樣:

$(document).on('click', '.a', function(e){ 
    history.pushState(null, null, this.href); 
    replacePag(this.href); 
    e.preventDefault(); 
    $(window).bind('popstate', function(){ 
     replacePag(location.pathname); 
    }); 
}); 

需要綁定到文檔作爲他們加入到拿起新的元素。

希望這會有所幫助。

+0

嗯,不,它沒有工作。我也嘗試過。 – Darkness

+0

道歉,我把它看作'a'元素,而不是'.a'的類,嘗試更新後的代碼:) –

+0

是的,我嘗試更改爲.a – Darkness