I am writing a game using jQuery. It is required to bind a function, for each element of the set (in my case - table cells), activated by pressing a key on the keyboard, if the cursor points to this element. For example, pressing "A" deletes all items that have the same class as the item that the cursor points to.

How can this be implemented?

    1 answer 1

    $(document).ready(function(){ $(document).keyup(function(e){ if(e.which == 65 /* Код кнопки А (латиница)*/){ var $table = $("#table"); var $active = $table.find("td:hover"); if($active.length > 0){ var code = parseInt($active.attr("data-key")); if(code > 0){ $table.find('td[data-key="' + code + '"]').attr("data-key", 0); console.log(code); } } } }); }); 
     table { width: 300px; background: #ccc; } table td { width: 75px; height: 75px; background: #fff; } table td[data-key="0"] { background: #fff; } table td[data-key="1"] { background: #f00; } table td[data-key="2"] { background: #0f0; } table td[data-key="3"] { background: #00f; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table cellpadding="0" cellspacing="1" id="table"> <tr> <td data-key="0"></td> <td data-key="1"></td> <td data-key="3"></td> <td data-key="1"></td> </tr> <tr> <td data-key="2"></td> <td data-key="1"></td> <td data-key="3"></td> <td data-key="0"></td> </tr> <tr> <td data-key="3"></td> <td data-key="2"></td> <td data-key="0"></td> <td data-key="0"></td> </tr> <tr> <td data-key="0"></td> <td data-key="1"></td> <td data-key="2"></td> <td data-key="3"></td> </tr> </table> 

    For example, cells are identified by a data-key : data-key = 0 - quiet state