如何使用 jquery 在引导程序中激活导航栏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17717025/
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 nav bar in bootstrap with jquery
提问by Fred
I want make the navbar active when i click it,,
我想让导航栏在我点击时激活,,
Here is the jquery i use
这是我使用的 jquery
$(document).ready(function () {
$('.navbar li').click(function(e) {
$('.navbar li').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
});
But because the preventDefault
i can't go to the link that i want. It just make the navbar active, but it's not go to the link that i choose.
但是因为preventDefault
我无法转到我想要的链接。它只是使导航栏处于活动状态,但不会转到我选择的链接。
And here is the link code :
这是链接代码:
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href='<?php echo site_url(' tampilan ') ?>'>Knowledge Base</a>
</li>
<li><a href='<?php echo site_url(' ticketing/browse_ticketing ') ?>'>Ticketing</a>
</li>
<li><a href='<?php echo site_url(' user/logout ') ?>'>Logout</a>
</li>
</ul>
</div>
if i dont use preventDefault()
the navbar won't active, but if i use it i can't go to the link i want..
如果我不使用preventDefault()
导航栏将不会激活,但如果我使用它,我将无法转到我想要的链接..
回答by Fred
Change the jQuery script to this:
将 jQuery 脚本更改为:
<script type="text/javascript">
$(document).ready(function () {
var url = window.location;
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().addClass('active');
});
</script>
回答by Loken Makwana
You can use following javascript to add active class based on current url
您可以使用以下 javascript 根据当前 url 添加活动类
I am assuming you are working with codeigniter so uri_string() function is available
我假设您正在使用 codeigniter,因此 uri_string() 函数可用
$(document).ready(function () {
var active_link = $('.navbar li a[href~="<?= uri_string() ?>"]');
if(active_link.size() > 0) active_link.parent().parent().addClass('active');
});
回答by Sanjeev Rai
Form you question, what I have got is you want to set active
class to li
and then redirect to some other page. If I'm understanding it right, then,
形成你的问题,我得到的是你想将active
类设置为li
然后重定向到其他页面。如果我理解正确,那么,
It looks like you are approaching it in a wrong way. You are trying to set active
class to li
first and then redirect to different page. This won't work anyway as after redirection active
class will not maintained automatically.
看起来你以错误的方式接近它。您正在尝试将active
class设置为li
first,然后重定向到不同的页面。这无论如何都不起作用,因为重定向active
类不会自动维护。
So, Correct way is to put active
class logic on target page only i.e. first navigate to the target page and there you can set active
class to li
.
因此,正确的方法是active
仅将类逻辑放在目标页面上,即首先导航到目标页面,然后您可以将active
类设置为li
.