current class removed when refreshing page

梦想与她 提交于 2021-02-05 09:33:29

问题


I have created a dynamic link list in one page...

When a click is done on one link on that dynamic list i want to show to user that link is active, so i will add one class to the clicked link but that new class removed suddenly when page refreshing.

I want to keep that class till user click another one link. How can i achieve?

My code is given below :

<style>
.activearea {
     background: #3f7aa5 !important;
}
</style>

<script>
$(document).ready(function() {
    $('a.areamenu').click(function(){
        $('a.areamenu').removeClass("activearea");
        $(this).addClass("activearea");
     });
});
</script>

This is my dynamic link

<li>
    <a class="areamenu" href="/areas/'.$categorynameNavLink.'/'.$subcatnameNAV.'/'.$subcatid.'/">'.$subcatname.'</a>
</li>

回答1:


Try to use localstorage() like,

$(function(){
    // if localstorage activeArea is set then add activearea class to menu
    if(localStorage && localStorage.getItem('activeArea')==1){
       $('a.areamenu').addClass("activearea");
    } 
    $('a.areamenu').click(function(){
       $('a.areamenu').removeClass("activearea");
       $(this).addClass("activearea");
       localStorage.setItem('activeArea',1);// set value in localstorage
    });
});



回答2:


Changing the class via AJAX only stores the information locally. So, whenever you refresh the page, this data is lost.

To get around this, you could get your page to remember this by setting a cookie.




回答3:


try it with PHP script like below,

Assuming page URl will be like: http://example.com/areas/categorynameNavLink/subcatnameNAV/123

<?php
$CatSelectID =  end(explode('/',curPageURL()));
?>

<li>
<a <?php if($subcatid == $CatSelectID) echo 'class="areamenu"';?> href="/areas/'.$categorynameNavLink.'/'.$subcatnameNAV.'/'.$subcatid.'/">'.$subcatname.'
</a>
</li>

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>

Note: not tested




回答4:


In click function use e.preventDefault()



来源:https://stackoverflow.com/questions/21330447/current-class-removed-when-refreshing-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!