javascript - Add class selected relative URL -
i'm trying make highlight class selected category:
this code :
<div id="category"> <ul> <a href="category.php?c=electronic"> <li>electronic</li> </a> <a href="category.php?c=fashion"> <li>fashion</li> </a> </ul> </div>
css:
.selected {border-bottom:3px solid red; }
script:
$("#category ul a").each(function(){ if ($(this).attr("href") == window.location.href){ $(this).addclass("selected"); } });
when click on electronic category, show highlight class .selected, but, problem came when url page change category.php?c=electronic&page=2
highlight class .selected not showing anymore, how modify jquery, so, show again? found javascript split url article, work problem?
use .indexof instead.
var url = $(this).attr("href"); var windowurl = window.location.href; if (windowurl.indexof(url) != -1){ $(this).addclass("selected"); }
$("#category ul a").each(function() { var url = $(this).attr("href"); var windowurl = "category.php?c=electronic&page=2"; console.log(windowurl, url, windowurl.indexof(url)); // <--- see how values change if (windowurl.indexof(url) != -1) { $(this).addclass("selected"); } });
.selected { color: red; border-bottom: 3px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="category"> <ul> <a href="category.php?c=electronic"> <li>electronic</li> </a> <a href="category.php?c=fashion"> <li>fashion</li> </a> </ul> </div>
Comments
Post a Comment