2012-07-19 103 views
0

我的頁面名稱是index.php,它包含一些鏈接(內部頁面鏈接)和內容。點擊鏈接我申請"selected" class鏈接li並顯示相關內容和我的頁面鏈接從index.php更改爲index.php#c2(或#c3,#c4,其他id的c1)。如何從URL中獲取查詢字符串

我的問題是在頁面加載。如果我在其他頁面給這個鏈接,例如。在page.php我給這樣的<li><a href="index.php?#c2">link2</a></li>然後我怎麼可能知道#c2通過URL在此基礎上我想申請"selected" classli。我嘗試了$_SERVER但未完成。 「?」之後我無法得到字符串。

請告訴我,如果有任何其他的方式做到這一點..

<li class="selected"><a href="#c1">link1</a></li> 
<li><a href="#c2">link2</a></li> 
<li><a href="#c3">link3</a></li> 
<li><a href="#c4">link4</a></li> 

<div id="c1"><!-- contents of link1 --></div> 
<div id="c2"><!-- contents of link2 --></div> 
<div id="c3"><!-- contents of link3 --></div> 
<div id="c4"><!-- contents of link4 --></div> 

jQuery代碼添加選定類

$('.links a').click(function(){ 
    $('.links a').parent().removeClass('selected'); 
    $(this).parent().addClass('selected'); 
}); 

在此先感謝..

+0

重複! http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript - http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery?lq=1 – Undefined 2012-07-19 11:02:03

+0

請參考這個答案 http://stackoverflow.com/questions/298503/how-can-you-check-for-a-hash-in-a--url-using-javascript – 2012-07-19 11:05:45

回答

3

你可以用」不要在PHP中這樣做,只是因爲它是一個客戶端機制,PHP在服務器上:) 你必須直接用JS解析你的查詢字符串。

嘗試這樣:

$('a [href='+document.location.hash+']').parent().addClass('selected'); 
+0

謝謝@Vincent,它非常好,解決方案簡單 – 2012-07-19 14:22:53

1

,我認爲這會工作... 例如,對於

example.com/page.html#anchor 
example.com/page.html#anotheranchor 

sol'n是...

if(window.location.hash) { 
    // Fragment exists 
} else { 
    // Fragment doesn't exist 
} 
+0

儘管它的查詢字符串,請參閱OP - >「?#c2」 – Undefined 2012-07-19 11:08:16

+0

http://stackoverflow.com/questions/298503/how-can-you-check-for-a-hash-in-a-url-使用-javascript – 2012-07-19 11:12:46

+0

謝謝@RajanRawal .. – 2012-07-19 14:23:50

0

可以在服務器腳本或javaScript中使用regexp,而不是爲每個元素定義clss。 只需使用下面給出的正則表達式模式,它將只給出URL中的鏈接部分。

 ^.*index.php/?(.*)$ 

要了解如何在JavaScript中使用RegExp Object,請點擊此鏈接。