2016-09-19 92 views
0

我在我的HTML中有以下錨點標記,用於從該HTML位置將內容加載到當前頁面上的contents div。這種定位的標籤是引導樹形插件的一部分,我用生成的內容表:保持錨點標記href跳轉到它的頁面

<a href="/Introduction/index.html#1-1-overview1" style="color:inherit;">1.1 Overview</a> 

在我的JavaScript,我有下面的代碼,我用它來聽兩個事件。一爲錨標記,這樣我禁用默認的行爲和其他處理的定位標記並加載內容和滾動到錨如下:

$("a[href*='#']").click(function(e) { 
     e.preventDefault(); 
    }); 

    // Add smooth scrolling to all links inside a navbar 
    $treeview.on('nodeSelected', function (e, data) { 
     e.preventDefault(); 

     if (data && data.href !== "") { 
      // Split location and hash 
      var hash = data.href.match(/[#].*/g)[0]; 
      var location = data.href.match(/[^#]*/g)[0]; 

      if (prevLocation === location) { 
       // Don't reload page if already at same location as last clicked 
       $('html, body').animate({ 
        scrollTop: $(hash).offset().top - 55 
       }, 200); 
      } else { 
       prevLocation = location; 
       $('#contents').load(location, function() { 
        $('html, body').animate({ 
         scrollTop: $(hash).offset().top - 55 
        }, 200); 
       }); 
      } 

     } 
     $body.scrollspy('refresh'); 
     $sideBar.affix('checkPosition'); 
    }); 

我所看到的是,第一次點擊我的TOC中的一個節點,它按預期將HTML加載到內容div中,但是第二次單擊它時,它會加載在錨標記中引用的HTML頁面,儘管我努力跟蹤是否以前加載過它,上面的條件邏輯。我還注意到,在隨後的點擊中,錨選擇器未被調用。

任何想法如何讓TOC最初將HTML從另一個頁面加載到當前頁面,然後在隨後的調用中滾動到錨點位置(即章節)?

+1

你嘗試'返回false;'以及'preventDefault'? – DavidG

+0

您可以使用chrome的開發人員工具調試它,看看prevLocation每次的價值是什麼? – klikas

+1

'return false'導致'nodeSelected'事件沒有被調用,但是如果我將這兩個函數結合在錨點選擇器下,消除'nodeSelected'事件並返回false,那麼它看起來很有效! – occasl

回答

0

結合使用這兩種功能,並返回false似乎工作如下:

 $("a[href*='#']").click(function(e) { 
     e.preventDefault(); 

     if (this && this.href !== "") { 
      // Split location and hash 
      var hash = this.href.match(/[#].*/g)[0]; 
      var location = this.href.match(/[^#]*/g)[0]; 

      if (prevLocation === location) { 
       // Don't reload page if already at same location as last clicked 
       $('html, body').animate({ 
        scrollTop: $(hash).offset().top - 55 
       }, 200); 
      } else { 
       prevLocation = location; 
       $('#contents').load(location, function() { 
        $('html, body').animate({ 
         scrollTop: $(hash).offset().top - 55 
        }, 200); 
       }); 
      } 

     } 
     $body.scrollspy('refresh'); 
     $sideBar.affix('checkPosition'); 
     return false; 
    }); 
+1

通常情況下,使用別人的評論回答問題的方式非常差,您應該給他們一個機會來首先添加自己的答案。 – DavidG

+0

LOL ...請儘管回答。我會刪除這一個,並給你信用。對不起,我搶先了你。 – occasl

+0

沒有必要,你已經做到了,你可以在這裏接受你自己的答案。我老實說不關心信用卡或代表,只是讓你知道有些人可能反應不好。 – DavidG