我的页面名称是index.php,它包含一些链接(内部页面链接)和内容。点击链接,我将"selected" class
应用于链接li
并显示相关内容,我的页面链接从index.php更改为index.php#c2(或其他id的#c3、#c4、c1)。
我的问题是页面加载。如果我在其他页面中给出这个链接,例如在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');
我认为这会起作用。。。例如
example.com/page.html#anchor
example.com/page.html#anotheranchor
sol'n是…
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
您可以在服务器脚本或javaScript中使用regexp,而不是为每个元素定义clss。只需使用下面给出的regexp模式,它将只提供URL中的链接部分。
^.*index.php/?(.*)$
要了解如何在JavaScript中使用RegExp对象,请单击链接。