2016-04-02 27 views
0

我在每個li中都有單個字符的無序列表。如果用戶按下鍵盤上的任何字母,我想將css類添加到頁面上的相應li。如果用戶按下鍵盤上的A,我想找到具有作爲其內容的Li和添加CSS類到它如何在按鍵中添加css類到li

<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 
    } 
+0

請你的HTML代碼添加到這個問題,你已經寫嘗試此實現自己的JS代碼一起。目前你的問題是'爲我寫'我的代碼',很可能會被關閉。 –

回答

2

不要使用按鍵,而是使用鍵控。詳情請看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>