在引用公共html頁面時,爲了便於知道當前所處的頁面,咱們每每在當前的頁面採用特定的樣式(如在當前頁面的列表中加active class),實現原理是當a 的href的屬性與document.location.href一致時在a 所在的列表中增長active classjavascript
<html> <head></head> <body> <li class="treeview"> <a href="#"> <i><img src="../../dist/img/admin-shezhi.png" width="20" height="20" /></i> <span>系統設置</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li class=""><a href="index3page1.html">驅動註冊</a></li> <li><a href="index3page2.html">遠程數據庫</a></li> <li><a href="#">報警設置</a></li> <li class=""> <a href="#">服務接口 <i class="fa fa-angle-left pull-right"></i></a> <ul class="treeview-menu menu-open"> <li><a href="#"><i class="fa fa-angle-double-right"></i>Modbus Tcp</a></li> <li><a href="#"><i class="fa fa-angle-double-right"></i>Weather Server</a></li> <li><a href="#"><i class="fa fa-angle-double-right"></i>Control Server</a></li> <li><a href="#"><i class="fa fa-angle-double-right"></i>Share Pipe Xml</a></li> </ul> </li> </ul> </li> </body> </html>
<script> $(function () { var currenturl = document.location.href; //alert(currenturl); var currentIndex; var atotal= $(".treeview a"); var alength=$(".treeview a").length; for(var i =0;i<alength;i++){ var attr=atotal.eq(i).attr("href"); //alert(attr); if(currenturl.indexOf(attr)!=-1){ currentIndex=i; } } atotal.eq(currentIndex).parents("li").addClass("active"); }); </script>