Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Keeping the dropdown open after selecting dropdown element

The dropdown menu which is being used is of bootstrap. The code is as below

<li id="changethis" class="dropdown">
 <a  href="#" class="dropdown-toggle" data-toggle="dropdown">LINK</a>
  <ul class="dropdown-menu">
   <li id="clickme"><a href="#">Link1</a></li>
   <li><a href="#">Link 2</a></li>
   <li><a href="#">Link 3</a></li>
  </ul>
 </a>
<li>

Jquery code looks like this

$(document).ready(function () {
 $('#clickme').on('click', function () {
    $('#changethis').removeClass('dropdown');
    $(this).addClass('dropdown open');
 });
});

On click of Link1, I wish to change the li class to dropdown open. I am not getting any error in my console, but the dropdown class is not changed.


Bootply Link

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

As Jack pointed out, you should be able to handle the click on your list item and prevent it from bubbling up with event.stopPropagation() like this:

$('#clickme').click(function (e) {
  e.stopPropagation()
});

Demo in Stack Snippets:

$('#clickme').click(function (e) {
  e.stopPropagation()
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>

<div id="changethis" class="dropdown">
  
  <a  href="#" class="dropdown-toggle" data-toggle="dropdown">
    Dropdown <span class="caret"></span>
  </a> 

  <ul class="dropdown-menu">
    <li id="clickme"><a href="#">Link1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
  </ul>

</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...