2010-03-05 181 views
1

爲了解決這個問題,我有兩個頁面。簡化,他們可以用這種方式表示。在DOM準備就緒之前,在另一個頁面上的內容定位到另一個頁面之後

<html> 
    <a href="page-2.html#section-A">Link to section A</a> 
</html> 

第2頁

<html> 
    <script>   
     // Assume jQuery 
     $(document).ready(function(){ 
      $('#wrapper').append($('<a name="section-A">Here is Section A</a><p>Some more content here.</p>')); 
     }); 
    </script> 
    <div id="wrapper"></div> 
</html> 

這樣做的問題是,當你點擊鏈接在1該網址,說:「http://www.mydomain.com/page-2.html#section-A」是其次,但內容直到DOM加載之後纔會生成錨鏈接,考慮到首先加載URL,這太晚了。

如果問題不明確,讓我知道,我會試圖進一步澄清,但如果任何人有任何關於如何得到這樣的場景的初步想法,請讓我知道。

回答

1

在第二頁中,「就緒」處理程序中的代碼可以檢查頁面位置。如果該位置有類似「#wrapper」的內容,那麼您的JavaScript可以重置該位置。

$(document).ready(function(){ 
    $('#wrapper').append($('<a name="section-A">Here is Section A</a><p>Some more content here.</p>')); 
    if (document.location.hash === '#wrapper') 
    document.location.hash = '#wrapper'; 
}); 

我會試試看看它是否真的有效。這裏:-)

編輯 OK是一個測試頁面:http://gutfullofbeer.net/hash1.html

有兩個環節:一個擁有它的哈希(「#hello」在我的情況),另外一個沒有。當你點擊第二個時,你會注意到你看到頁面底部的「hello」部分。當你點擊第一個頁面時,你會進入同一頁面,但「你好」部分將不可見(除非你的瀏覽器窗口真的很大)。

相關問題