如何在按键上添加css类到li

时间:2016-04-02 20:25:04

标签: jquery

我的每个li都有单个字符的无序列表。如果用户按下键盘上的任何字母,我想将css类添加到我页面上的相应li。如果用户按下键盘上的A,我想找到以A为内容的li并向其添加css类

    <div>
      <ul class ='list'>
       <li>a</li>
       <li>b</li>
       <li>c</li>
       ...
       <li>z</li>
      </ul>
    </div>

这就是我开始的方式

      $(document).keypress(function(e){
      var x = e.which;
      if((x >= 65 && x <= 90)||(x >=97 && x <= 122)||(x >=48 && x <= 57)) {
         checkfirst(x);

       }
      });
     // pick list item with the text content of the value passed
     function checkfirst(x){
       var y = $('.list').find('li');
       // code will go here
       //am trying to find the li with text equal to the argument passed
     }

1 个答案:

答案 0 :(得分:2)

不要使用按键,而是使用keyup。有关详细信息,请阅读此帖Key event differences

我创建了一个函数来在文档上按下的字符对应于菜单行的内容时添加一个活动的类。

$(document).on('keyup', function(e) {
  if (e.shiftKey == false && e.ctrlKey == false) {
    // get the character typed
    var charTyped = String.fromCharCode(e.which);

    // remove style active from all li with no child and add this to the elements with the
    // content matching the character typed
    $('div ul.list li:not(:has(*))').removeClass('active').filter(function() {
      return this.textContent.toUpperCase() == charTyped;
    }).addClass('active');
  }
});
.list {
  font-family: Verdana, sans-serif;
  font-size: 12px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.list li {
  background: yellowgreen;
  display: block;
  width: 150px;
  height: 30px;
  margin: 2px 0;
  font-size: large;
}
.active {
  background-color: #54BAE2 !important;
}
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<div>
    <ul class ='list'>
        <li>a</li>
        <li>b</li>
        <li>c</li>
        ...
        <li>z</li>
    </ul>
</div>