Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - How to have a page support to typing keyboard to launch a modal?

This link would launch a jupyter notebook.

enter image description here

When the page is loaded,

typing h, would launch a modal ("Keyboard shortcuts")

enter image description here

typing f, would launch another modal "Find and Replace"

enter image description here

How to have a page support to typing keyboard to launch a modal?

This link gives some inspiration inside modal.

This and this give examples about a single element, although I am asking an approach to listen keypress event on whole page

question

Here is my code which is trying to listen any keypress

<!DOCTYPE html>
<html>

<head>
    <script>
        i = 0;
        $(document).querySelector('#myDiv').addEventListener('keyup', function (e) {
            $("span").text(i += 1);
        })
    </script>
</head>

<body>
    <div class="container" id="mydiv" tabindex="0">
        <p>Keypresses: <span>0</span></p>
    </div>

</body>

</html>

How to make this code work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are wiring the event incorrectly. With jQuery, use on() to wire the event and provide the selector for your target element in the second argument:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    i = 0;
    $(document).on('keyup', '#mydiv', function(e) {
      $("span").text(i += 1);
    })
  </script>
</head>

<body>
  <div class="container" id="mydiv" tabindex="0">
    <p>Keypresses: <span>0</span></p>
  </div>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...