将活动类从bootstrap添加到li元素
Adding active class from bootstrap to li element
你好,我想问为什么我的代码不工作。我在rails上使用ruby,带有bootstrap和haml。
下面是我的javascript代码:
:javascript
$(".nav navbar-nav li a").click(function() {
$(this).parent().addClass('active').siblings().removeClass('active');
});
这是我的导航栏代码:
%nav.navbar.navbar-inverse
.container-fluid
.navbar-header
%img.image{:alt => "Ruby Logo", :src => "http://www.rossconf.io/images/projects/ruby-2779abad.png"}
= link_to "Users", users_path, class: 'navbar-brand'
#bs-example-navbar-collapse-1.collapse.navbar-collapse
%ul.nav.navbar-nav
%li
%a{:href => addresses_path}
Addresses
%span.sr-only (current)
%li
%a{:href => imports_path}
Import addresses
%span.sr-only (current)
- if current_user
%li
%a{:href => logout_path}
Logout
%span.sr-only (current)
- else
%li
%a{:href => login_path}
Login
%span.sr-only (current)
知道为什么它运行没有错误,但什么都没有发生吗?
我猜你的代码有错误:
应该是:
$(".nav.navbar-nav li a").click(function() {
//-----^^-------missed a class selector here and you can see a space too
$(this).parent().addClass('active').siblings().removeClass('active');
});
首先,您错过了在选择器中加入类。第二件事是,如果你想在点击链接时添加活动类,那么有两种可能的解决方案:-
第一个解是
$(".nav .navbar-nav li a").click(function(event) {
event.preventDefault();
$(this).parent().addClass('active').siblings().removeClass('active');
});
第二个解决方案是:-
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$(".nav .navbar-nav li a ").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
请告诉我,如果我错了,不符合要求
相关文章:
- 完全可链接的li元素
- 使用li元素的html内容更改该元素的背景
- 需要在量角器中找到使用ng中继器的li元素的数量
- 根据输入值创建li元素
- 要更改变量的高度li元素
- 为li元素添加标题
- 在不使用sort()的情况下获取HTML LI元素的副本
- 将内容从 JSON 数组附加到 li 元素
- 获取 LI 元素的偏移宽度(或等效项)
- addClass 到当前 li 元素并删除类
- 使用纯JS点击即可从li元素中获取文本和id
- Rails-使用Ajax删除li元素
- 对具有相同类级别的不同li元素进行排序
- 显示/隐藏具有不同类的li元素
- 从ul中删除li元素
- 从OL中移除LI元素
- 删除不起作用的li元素
- 从javascript生成的li a元素触发onclick
- 如何使用json对象作为li元素的id属性或使用javascript锚定标记id
- 添加和删除jquery-li元素