如何从URL中获取查询字符串
我的页面名称是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" class
li
。我尝试了$_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');
});
在此先感谢..
你可以用”不要在PHP中这样做,只是因为它是一个客户端机制,PHP在服务器上:) 你必须直接用JS解析你的查询字符串。
尝试这样:
$('a [href='+document.location.hash+']').parent().addClass('selected');
谢谢@Vincent,它非常好,解决方案简单 – 2012-07-19 14:22:53
,我认为这会工作... 例如,对于
example.com/page.html#anchor
example.com/page.html#anotheranchor
sol'n是...
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
尽管它的查询字符串,请参阅OP - >“?#c2” – Undefined 2012-07-19 11:08:16
http://*.com/questions/298503/how-can-you-check-for-a-hash-in-a-url-使用-javascript – 2012-07-19 11:12:46
谢谢@RajanRawal .. – 2012-07-19 14:23:50
可以在服务器脚本或javaScript中使用regexp,而不是为每个元素定义clss。 只需使用下面给出的正则表达式模式,它将只给出URL中的链接部分。
^.*index.php/?(.*)$
要了解如何在JavaScript中使用RegExp Object,请点击此链接。
重复! http://*.com/questions/901115/get-query-string-values-in-javascript - http://*.com/questions/1403888/get-url-parameter-with-jquery?lq=1 – Undefined 2012-07-19 11:02:03
请参考这个答案 http://*.com/questions/298503/how-can-you-check-for-a-hash-in-a--url-using-javascript – 2012-07-19 11:05:45