2013-01-15 43 views
0

我有這個jQuery顯示/隱藏內容取決於點擊的列表項。我還希望能夠在登錄此頁面時顯示特定內容,具體取決於用戶在另一頁面上點擊的鏈接。從外部鏈接攜帶變量到頁面並插入到jQuery腳本onload

我知道爲了做到這一點,我必須以某種方式從另一個鏈接中繼承變量,並使其充當變量。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>  
<script type="text/javascript"> 
$(document).ready(function() { 
$('#side_nav ul li a').click(function() { 
    $('#side_nav ul li.current').removeClass('current'); 
    $(this).parent().addClass('current'); 

    var filterVal = $(this).attr('class'); 

     $('#content div.section').each(function() { 
      if($(this).hasClass(filterVal)) { 
       $(this).fadeIn(200); 
      } else { 
       $(this).hide(); 
      } 
     }); 
    return false; 
}); 
}); 
</script> 

我試着加入#desired_content在單獨的頁面上的鏈接URL的結束,我都知道,使用window.location.hash,我可以拉散列拉布勒作爲變量,但不知何故我迷失在了究竟如何實現這一點。

請幫忙。

編輯:我已將此添加外部頁面:

<li><a href="./about.html#how_it_works">HOW IT WORKS</a></li> 

,這到目標頁面,只是爲了測試是否添加類

<script type="text/javascript"> 
$(document).ready(function() { 
    var myHash = window.location.hash; 

    if(myHash == "#how_it_works"){ 
     $('#content div.how_it_works').addClass('test'); 
    }else if(myHash == "#option2"){ 
     // fade in option2 
    } 


});  
</script> 

我不明白爲什麼這個不工作...

回答

1

哈希網址大多被用於在頁面錨標籤(返回頁首等),所以我建議,指導別人到使用散列URL的頁面的某個部分,這很有意義。

我在頁面上做過的一切,都是通過window.location.hash抓取哈希URL,並根據這個字符串來操縱你的頁面。

var myHash = window.location.hash; 

if(myHash == "#desired_content"){ 
// fade in option1 
}else if(myHash == "#option2"){ 
// fade in option2 
} 
+0

你能舉個例子說明window.location.hash命令如何在這裏使用。 (它實際上並不是頁面上的一個錨點,但是需要在頁面加載時通過腳本運行一個變量以確保顯示正確的內容) – glenn

+0

您可以看看我上面的編輯嗎?不知道我做錯了什麼。 – glenn

+0

感謝@MarkDuiker - 讓它與您的標記一起工作! – glenn

-1

我會建議將變量存儲在第一頁的localStorage中,然後從第二頁的localStorage加載變量。它會更簡單,而不是傳遞散列URL,這不是正確的目的。

首頁

<a href="secondPage.html" id="link">Go to second page</a> 
<script type="text/javascript"> 
$(document).ready(function() { 
$('#link').click(function(){ 
    // set your variable when someone click the link 
    localStorage.setItem("myVariable", "someValue"); 
}); 
}); 
</script> 

第二頁

<script type="text/javascript"> 
$(document).ready(function() { 
var yourVariable = localStorage.getItem("myVariable"); 
// do your stuff according to this variable that passed from firstpage 
//... 
}); 
</script> 
相關問題