项目未在下拉菜单中选择

时间:2017-09-07 13:14:56

标签: javascript html css select drop-down-menu

使用bootstrap,我选择了下拉菜单,但它没有工作,所选项目没有出现在列表的顶部。



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group">
<button type="button" class="form-control btn btn-default dropdown-toggle" data-toggle="dropdown">
    Select Business type <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
    <li><a href="#">small</a></li>
    <li><a href="#">medium</a></li>
    <li><a href="#">large</a></li>
</ul>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您需要一些JavaScript来存储按钮中所选选项的文本值。

由于您已经在使用jQuery,因此可以绑定到列表项的click事件,然后将该项的文本复制到该按钮的文本值。

但是,您还必须保留小插入符<span class="caret"></span>,以便您可以创建模板或只复制它并在文本更改后附加它。

在下面的示例中,我使用了find / append选项。

$('.dropdown-menu li').on('click', function() {
  var $dropdown = $('.dropdown-toggle');
  var text = $(this).text();
  var $span = $dropdown.find('span');
  
  $dropdown.text(text).append($span);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="btn-group">
  <button type="button" class="form-control btn btn-default dropdown-toggle" data-toggle="dropdown">
    Select Business type <span class="caret"></span>
</button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">small</a></li>
    <li><a href="#">medium</a></li>
    <li><a href="#">large</a></li>
  </ul>

如果你想变得更加漂亮,你可以将“模板”存储在变量中并重复使用它,类似于:

var dropdownTextTemplate = '{0} <span class="caret"></span>'

$('.dropdown-menu li').on('click', function() {
  var $dropdown = $('.dropdown-toggle');
  var text = $(this).text();
  var $span = $dropdown.find('span');
  
  $dropdown.html(dropdownTextTemplate.replace('{0}', text));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="btn-group">
  <button type="button" class="form-control btn btn-default dropdown-toggle" data-toggle="dropdown">
    Select Business type <span class="caret"></span>
</button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">small</a></li>
    <li><a href="#">medium</a></li>
    <li><a href="#">large</a></li>
  </ul>