bootstrap下拉列表中的选定选项无效

时间:2017-11-09 03:38:53

标签: jquery twitter-bootstrap

我尝试了一些可能的解决方案,从我的引导程序导航栏的下拉列表中获取所选项目,但它似乎不起作用。非常感谢。感谢。

下面是下拉列表的截图

enter image description here

<li class="nav-item active dropdown">
        <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" 
        aria-haspopup="true" aria-expanded="false"><i class="fa fa-globe" aria-hidden="true"></i>
         Language<span id="selected" class="caret"></span></a>
         <div class="dropdown-menu" aria-labelledby="languageDropdown">
          <a class="dropdown-item" href="#">English</a>
          <a class="dropdown-item" href="#">中文</a>
        </div>
      </li>

Jquery的

<script>
 $('.dropdown-menu a').click(function(){
    $('#selected').text($(this).text());
  });
</script>

我试图为我的其他下拉列表添加另一个功能。当我单击其中一个下拉列表时,另一个也会更改。

 <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" 
        aria-haspopup="true" aria-expanded="false"><i class="fa fa-sort-amount-asc" aria-hidden="true"></i>
        <span id="sort" class="caret">Sort</span></a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Category</a>
          <a class="dropdown-item" href="#">Date and Time</a>
          <a class="dropdown-item" href="#">Availability</a>
        </div>
      </li>



   <script>
 $('.dropdown-menu a').click(function(){
    $('#selected').text($(this).text());
$('.dropdown-menu a').click(function(){
    $('#sort').text($(this).text());

  });
</script>

1 个答案:

答案 0 :(得分:0)

  1. 使用班级选择范围。
  2. 使用.closest()获取li
  3. 使用.find()获取范围
  4. $('.dropdown-menu a').click(function() {
      $(this).closest('li').find('.caret').text($(this).text());
    
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
    
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fa fa-sort-amount-asc" aria-hidden="true"></i>
            Sort<span id="sort" class="caret"></span></a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Category</a>
          <a class="dropdown-item" href="#">Date and Time</a>
          <a class="dropdown-item" href="#">Availability</a>
        </div>
      </li>
      <li class="nav-item active dropdown">
        <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fa fa-globe" aria-hidden="true"></i>
             Language<span id="selected" class="caret"></span></a>
        <div class="dropdown-menu" aria-labelledby="languageDropdown">
          <a class="dropdown-item" href="#">English</a>
          <a class="dropdown-item" href="#">中文</a>
        </div>
      </li>
    
    
    </ul>