我不是javascript高手,但我需要创建一个脚本来满足以下要求。
If body id=“索引”将类“current-selected”添加到锚定标签where href=index.php If body id=“服务”将class="current-selected“添加到锚定标签where href=services.php等。
这有什么意义吗?有人能帮上忙吗?
如果可以的话,谢谢!
Abbotsford Web Design
发布于 2009-12-18 05:40:23
在Using Jquery to add/remove a class based on body Id上构建:
var bodyID = $('body').attr('id');
$("a[href$='" + bodyID + ".php']").toggleClass('current-selected'); //add/remove或
$("a[href$='" + bodyID + ".php']").addClass('current-selected'); //add我们不使用"=",而是使用"$=“(指"href$=")语法,它将匹配字符串的结尾,因此"index.php”和"/index.php“都将由"index.php”匹配。
要在您的站点上实现它,您需要在jQuery ready函数中运行上述代码,以便在Javascript对其执行操作之前加载脚本块下的所有HTML:
编辑:这适用于站点的所有主/顶部导航链接(用于匹配href的字符串是URL的最后一个路径段):
<script type="text/javascript">
$(document).ready(function(){
page = window.location.pathname.substring(1).replace(/\//g,'');
$("a[href*='" + page + "']").addClass('current-selected');
});
</script>发布于 2009-12-18 05:35:15
像这样的东西应该能起到作用。这将动态地确定您的body元素ID,并更改引用同名的php文件的所有锚标记。
var bodyID = $("body").attr("id");
$("a[href='" + bodyID + ".php']").addClass("current-selected");正如在另一条注释中所指出的,使用.removeClass("current-selected")函数来完成相反的操作。
另外,如果你的网址只以"index.php“结尾,即href属性类似于"/ something /index.php",那么使用"a[href$='" + bodyID + ".php']”作为选择器。它将匹配以文件名结尾的href值。
发布于 2009-12-18 05:34:07
假设您的正文ID并不总是与其相应链接的文件名完全匹配,您可以这样做。
$("body#index a[href='index.php']").addClass("current-selected");
$("body#service a[href='service.php']").addClass("current-selected");如果主体ID始终与相应的链接href值匹配,则可以首先提取主体ID,并将其用作jQuery选择器中的变量:
var body_id = $("body").attr("id");
$("a[href='"+body_id+".php']").addClass("current-selected");https://stackoverflow.com/questions/1924723
复制相似问题