使用当前代码,当我按下某个选项的第一个字母时,控件就出现了,但是如果我先按下该选项将不起作用:该选项的两个或三个或四个字母,即列表中的某个选项是“ Jquery” ,那么当我仅按下J时,控件就出现了,但是当我连续按下J和q或连续按下J,q,e时,控件就消失了。我想将此功能添加到下拉列表中,所以请帮忙。

jQuery函数:

$('#cars').on('shown.bs.dropdown', function () {

    var $this = $(this);

    $(document).keypress(function (e) {
        var key = String.fromCharCode(e.which);

        $this.find('li').removeClass('active').filter(function() {
            return $(this).text().charAt(0).toLowerCase() === key;
        }).first().addClass('active');

    });

    $('#').on('hide.bs.dropdown', function () {
        $(document).unbind("keypress");
    });
});


HTML代码:

<div class="btn-group dropdown" id="cars">
<a data-toggle="dropdown" class="btn btn-inverse dropdown-toggle">Models<span class="caret"></span></a>
  <ul class="dropdown-menu">
<li><a class="hc" href="#">Volvo</a></li>
<li><a class="hc" href="#">Saab</a></li>
<li><a class="hc" href="#">Mercedes</a></li>
<li><a class="hc" href="#">Polo</a></li>
<li><a class="hc" href="#">Vento</a></li>
<li><a class="hc" href="#">Zen</a></li>
<li><a class="hc" href="#">Nano</a></li>
<li><a class="hc" href="#">Fortuner</a></li>
<li><a class="hc" href="http://www.audi.com/">Audi</a></li>
  </ul>
</div>

最佳答案

我想你在找什么



var $this = $('#cars');

var timer, chars = '';
$(document).keypress(function(e) {
  var key = String.fromCharCode(e.which);

  if (timer) {
    chars += key;
  } else {
    chars = key;
  }
  console.log('searc', chars)

  var regex = new RegExp('^' + chars, 'i');

  $this.find('li').removeClass('active').filter(function() {
    return regex.test($(this).text());
  }).first().addClass('active');

  timer = setTimeout(function() {
    chars = '';
    timer = undefined;
  }, 500)

});

.active a {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="btn-group dropdown" id="cars">
  <a data-toggle="dropdown" class="btn btn-inverse dropdown-toggle">Models<span class="caret"></span></a>
  <ul class="dropdown-menu">
    <li><a class="hc" href="#">Volvo</a></li>
    <li><a class="hc" href="#">Saab</a></li>
    <li><a class="hc" href="#">Mercedes</a></li>
    <li><a class="hc" href="#">Polo</a></li>
    <li><a class="hc" href="#">Vento</a></li>
    <li><a class="hc" href="#">Zen</a></li>
    <li><a class="hc" href="#">Nano</a></li>
    <li><a class="hc" href="#">Fortuner</a></li>
    <li><a class="hc" href="http://www.audi.com/">Audi</a></li>
  </ul>
</div>

关于jquery - 通过按键在下拉列表中选择选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28454811/

10-12 00:06
查看更多