浅谈下给类似导航栏的东东,添加停留样式的三种方法:
实例:
HTML代码:
<div class="side_layout">
<!--Sidebar content-->
<div class="list-group">
<a href="#" class="list-group-item active">项目1 <span class="glyphicon_right_img glyphicon glyphicon-chevron-right"></span></a>
<a href="#" class="list-group-item">项目2 <span class="glyphicon_right_img glyphicon glyphicon-chevron-right"></span></a>
<a href="#" class="list-group-item">项目3 <span class="glyphicon_right_img glyphicon glyphicon-chevron-right"></span></a>
<a href="#" class="list-group-item">项目4 <span class="glyphicon_right_img glyphicon glyphicon-chevron-right"></span></a>
<a href="#" class="list-group-item">项目5 <span class="glyphicon_right_img glyphicon glyphicon-chevron-right"></span></a>
<a href="#" class="list-group-item">项目6 <span class="glyphicon_right_img glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
js代码:
方法一:
$(function(){
$(".side_layout a").click(function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
});
方法二:
$(document).on("click", ".side_layout a", function(){
$(this).addClass('active')
.siblings().removeClass('active');
});
方法三:
$(function(){
$(".side_layout a").bind('click',function(){
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
});
个人认为方法二最方便。
方法一和三都需要包含在$(function()内部
方法二、三都是给元素绑定一个单击事件,区别在于$(document).on的方法是把绑定委托到了文档上,二bind方法是委托到了.side_layout a上,据查阅资料,前者效率更好~~~