简体   繁体   English

菜单标签的选择/活动样式取决于url,javascript函数中的file.php

[英]Menu tab selected/active style depending on the file.php in the url, javascript function

I'm currently using this: 我目前正在使用此:

<a href="t1.php" class="<?php if(end(explode("/", $_SERVER["PHP_SELF"])) == "t1.php") { echo 'active'; } else {} ?>">Tab2</a>
<a href="t2.php" class="<?php if(end(explode("/", $_SERVER["PHP_SELF"])) == "t2.php") { echo 'active'; } else {} ?>">Tab2</a>

But I dont like to use php this way and I think I'm wasting time processing this on php server side. 但是我不喜欢以这种方式使用php,我想我是在浪费时间在php服务器端进行处理。 Basically I want to make this in javaScript, when the page is loaded or loading, a javascript function trigers and change the class depending if the file.php in the url. 基本上,我想在javaScript中做到这一点,当页面被加载或加载时,一个javascript函数将触发并更改类,具体取决于URL中的file.php。 Also, please avoid all JQuery script/plugins and all that kind of stuff. 另外,请避免使用所有JQuery脚本/插件和所有此类东西。

Perhaps there is another way to do this efficiently? 也许还有另一种方法可以有效地做到这一点?

Hope I explained well. 希望我能解释清楚。 ~Thanks, I'm Human. 〜谢谢,我是人类。

If you could add to these elements an ID attr (just for easier manipulation), you could do something like this (attach script to onload of body or at the end of the script): 如果可以在这些元素上添加一个ID属性(只是为了更容易操作),则可以执行以下操作(将脚本附加到正文的加载或脚本的末尾):

<a href="t1.php" id="tab1">Tab2</a>
<a href="t2.php" id="tab2">Tab2</a>

JavaScript: JavaScript:

var ThisLocation = document.location.href;
if(ThisLocation.indexOf('t1.php') !== -1)
{
    document.getElementById('tab1').setAttribute('class', 'active');
}
else if(ThisLocation.indexOf('t2.php') !== -1)
{
    document.getElementById('tab2').setAttribute('class', 'active');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM