我在navbar
设计了Bootstrap
,我希望获得点击它的nav-item
的名称。我可以将其设置为当前活动但无法检索导航项的名称。怎么做到这一点?
我知道jQuery中的nodeName
获取节点的名称,但我想明确地获取该节点内的内容。
HTML
<div class="collapse animated fadeInLeft" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li>
<li class="nav-item"> <a class="nav-link" href="#">Features</a> </li>
<li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li>
<li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li>
</ul>
</div>
JS
$(document).ready(function () {
"use strict";
$('ul.navbar-nav > li').click(function (e) {
e.preventDefault();
var getItem = $(this);
$('ul.navbar-nav > li').removeClass('active');
$(this).addClass('active');
$(".navbar-brand").after(" <ul class=\"navbar-nav\"><li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\">" + getItem + "<span class=\"sr-only\">(current)<\/span><\/a> <\/li><\/ul> ");
$('.navbar-toggler').click();
});
});
我的当前输出为[object][object]
,但如果当前有效,我想获得Home
;如果当前有效,我想获得Pricing
。
PS:使用Bootstrap 4
答案 0 :(得分:3)
$(this)
是li
对象,您希望像这样使用$(this).text()
$('ul.navbar-nav > li').click(function (e) {
e.preventDefault();
var getItem = $(this).text();
$('ul.navbar-nav > li').removeClass('active');
$(this).addClass('active');
$(".navbar-brand").after(" <ul class=\"navbar-nav\"><li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\">" + getItem + "<span class=\"sr-only\">(current)<\/span><\/a> <\/li><\/ul> ");
$('.navbar-toggler').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse animated fadeInLeft" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li>
<li class="nav-item"> <a class="nav-link" href="#">Features</a> </li>
<li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li>
<li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li>
</ul>
</div>
<div class="navbar-brand"></div>
答案 1 :(得分:1)
您需要指定您想要从中获取的内容:$(this).text()或.html()