javascript 如何激活类 onclick 列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17720680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to active a class onclick list item
提问by Amy
I am facing a problem in which i want to add class onclick means the clicked should add class.
see my image
我面临一个问题,我想添加类 onclick 意味着点击应该添加类。看我的图片
i am doing this by jquery as:
我通过 jquery 这样做:
$(function() {
$('.box li').click(function(){
$('.box li').removeClass('submenu-active');
$(this).addClass('submenu-active');
});
});
and my css is:
我的 css 是:
.aside ul li.submenu-active a {background-color:#df0000; color:#fff;}
and my submenu code is:
我的子菜单代码是:
<ul class="box">
<li class="submenu-active"><a href="create_financial_year.php">Create Financial Year</a></li>
<li ><a href="select_financial_year.php">Select Financial Year</a></li>
<li><a href="account_master.php">Account Master</a></li>
<li><a href="bank_account_master.php">Bank Account Master</a></li> <!-- Active -->
<li><a href="subscription_master.php">Subscription Master</a></li>
<li><a href="subscription_fee_master.php">Subscription Fee Master</a></li>
<li><a href="member_master.php">Member Master</a></li>
<li><a href="membership_suspension.php">Membership Suspension</a></li>
</ul>
i realy Have spent so many hour but did not sort out this...by this it is working but when i leave click onmouse then the added class got remove...any suggestion would be highly responsive...thanxxx
我真的花了这么多小时但没有解决这个问题......通过这个它正在工作但是当我点击鼠标然后添加的类被删除......任何建议都会非常敏感......thanxxx
回答by A. Wolff
Use that instead:
改用它:
$(function () {
$('.box li a').click(function (e) {
e.preventDefault();
$(this).closest('li').addClass('submenu-active').siblings().removeClass('submenu-active');
//to load new content using ajax
//you could wish to show user, some content is loading
$('#myContainer').html('<img src="loading.gif>').load(this.href);
});
});
Corresponding CSS for your jsfiddle:
您的 jsfiddle 对应的 CSS:
ul.box li.submenu-active {
background-color:#df0000;
color:#fff;
}
Problem is then, anchor tags won't redirect to corresponding page, but i don't know what you are looking for exactly.
问题是,锚标签不会重定向到相应的页面,但我不知道你在寻找什么。