Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

jquery - Bootstrap access dropdown menuitem elements (name, href, text)

I have a Dropdown menu nested in order like this:

    <div class="navbar-collapse collapse" id="collapsingNavbar">
      <ul class="navbar-nav">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Sensors</a>
        <div class="dropdown-menu bg-dark" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#1">Sensor 1</a>
          <a class="dropdown-item" href="#2">Sensor 2</a>
          <a class="dropdown-item" href="#3">Sensor 3</a>
          <a class="dropdown-item" href="#4">Sensor 4</a>
          <a class="dropdown-item" href="#5">Sensor 5</a>
        </div>
    </div>

<p id="sensor_cur" class="small">Sensor 000</p>

I tried to access elements like this:

$('a.dropdown-item').on('click', function(e){
 e.preventDefault();
 var href = $('a.dropdown-item').attr('href');
 var element=document.getElementById("sensor_cur"); 
 element.innerHTML = href;
});

The issue is that I always getting #1 from href value no matter what menu-item I will click on.

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is because you're selecting all the .dropdown-item elements within the event handler. To access the href of the one which is clicked use the this keyword instead.

Also note that you can make the code more succinct by using jQuery to update the text in the #sensor_cur element. Try this:

$('a.dropdown-item').on('click', function(e) {
  e.preventDefault();
  var href = $(this).attr('href');
  $("#sensor_cur").text(href);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar-collapse collapse" id="collapsingNavbar">
  <ul class="navbar-nav">
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Sensors</a>
      <div class="dropdown-menu bg-dark" aria-labelledby="navbarDropdownMenuLink">
        <a class="dropdown-item" href="#1">Sensor 1</a>
        <a class="dropdown-item" href="#2">Sensor 2</a>
        <a class="dropdown-item" href="#3">Sensor 3</a>
        <a class="dropdown-item" href="#4">Sensor 4</a>
        <a class="dropdown-item" href="#5">Sensor 5</a>
      </div>
    </li>
  </ul>
</div>

<p id="sensor_cur" class="small">Sensor 000</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...