问题
I have a navbar
designed in Bootstrap
,I want to get the name of the nav-item
on which it was clicked. I can set it to active currently but unable to retrieve the name of the nav-item. How to achieve this?
I am aware of the nodeName
in jQuery which get the name of the node but I want to get the content inside of that node apparently.
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();
});
});
my Current output is [object][object]
butI want to get Home
if that is currently active or Pricing
if that is currently active.
PS:Using Bootstrap 4
回答1:
You need to specify what you want to get from the this, use $(this).text()
to get innerText, or $(this).html()
to get innerHtml.
回答2:
$(this)
is the li
object, you want to use $(this).text()
like this
$('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>
来源:https://stackoverflow.com/questions/41749293/get-the-name-of-the-nav-item-on-which-it-was-clicked