Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - How to make li active when the code of the list is reusable in other file

I am having a list which is reused in other webpage so i included it in one file and require the same in other webpage where required

I want to make them active for example if MY RESUME IS CLICKED THE li of myresume become active instead of dashboard so i implement jquery in the same file but everytime i click on other link other than dashboard the active class is only present in Dashboard l . Is it due to because every time I am going to other page the active class is present on dashboard or due to jquery code(i have included cdn of jquery)??

$(document).ready(function() {
  $("li").click(function() {
    // remove classes from all
    $("li").removeClass("active");
    // add class to the one we clicked
    $(this).addClass("active");
  });
});
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="active"><a href="dashboard.php"><i class="ti-dashboard"></i>Dashboard</a></li>
  <li><a href="resume.php"><i class="ti-wallet"></i>My Resume</a></li>
  <li><a href="employer-list.php"><i class="ti-wallet"></i>Browse Jobs</a></li>
  <li><a href="assess.php?q=1"><i class="ti-wallet"></i>Assessment</a></li>
  <li><a href="jobs.php"><i class="ti-hand-point-right"></i>Applied Jobs</a></li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want the active to stay, you COULD use sessionStorage, but why not just ajax the page

https://plungjan.name/SO/ajaxnav/index.html

$(document).ready(function() {
  $("#nav a").on("click", function(e) {
    e.preventDefault();
    // remove classes from all
    $("#nav li").removeClass("active");
    // add class to the one we clicked
    $(this).closest("li").addClass("active");
    $("#content").load(this.href);
  }).eq(0).click();
});
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="nav">
  <li class="active"><a href="dashboard.php"><i class="ti-dashboard"></i>Dashboard</a></li>
  <li><a href="resume.php"><i class="ti-wallet"></i>My Resume</a></li>
  <li><a href="employer-list.php"><i class="ti-wallet"></i>Browse Jobs</a></li>
  <li><a href="assess.php?q=1"><i class="ti-wallet"></i>Assessment</a></li>
  <li><a href="jobs.php"><i class="ti-hand-point-right"></i>Applied Jobs</a></li>
</ul>
<div id="content"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...