2013-09-29 37 views
0

我目前有一個問題,一個hashchange和jQuery手機衝突,所以我正在尋找手動更改網址,並自己處理請求。雖然
小問題,我目前使用:window.location無頁面加載

$('#test').click(function() { 
    window.location = "/test/#hash"; 
}); 

,因爲我希望它成功地改變URL,但隨後嘗試加載所請求的URL,我只是想改變網址,而不會提示頁面加載。這是可能嗎?任何建議將不勝感激!

回答

1

可以使用pushState的方法:

window.history.pushState({FOO: '欄'}, '其他頁面', '/測試/#散列');

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

要小心,這個功能不是由<支持= IE9

JAVASCRIPT

$('a').on('click', function(e) { 
    var element = $(this), 
     element_anchor = element.attr('href'), 
     element_title = element.attr('title'); 
    if (typeof window.history !== 'undefined') 
    { 
    window.history.pushState({anchor: element_anchor}, element_title, '/test/' + element_anchor); 
    } 
    e.preventDefault(); 
}); 

HTML

<a href="#first_page" title="this is the first page">first page</a> 
+0

這個偉大的工程,還有一兩件事,這是否可能? e將'#test'的'attr'追加到url中?例如點擊''test''attr'的值'test'會呈現這樣的URL:'/ test /#hash'? – user1374796

+0

用一個例子更新迴應;-) –