-->

Capturing of keydown events in a html page with fr

2020-03-26 08:49发布

问题:

I have a jsp page with frames

<%@ include file="/includes/taglibs.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
  <head>
  <title>Welcome</title>
    <script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $(this).keydown(function(e) {
                if(e.keyCode==27){
                    alert("escape pressed");
                    e.preventDefault();
                }
          });       
        }   
        );  
      </script> 
  </head>
      <frameset rows="42,*" frameborder="0" framespacing="0" id="framest">
          <frame src="/xyz/abc.html" scrolling="no" name="frame1"/>
          <frame src="/xyz/init.html" scrolling="no" name="frame2"/>
      </frameset>
</html>

I am trying to capture escape key press. But this doesn't seem to work. On each individual frame html if I write the same code of capturing , it works perfectly fine.

What changes should I make in the code above so that I would write the keydown code just once which enables me to capture keydown on anywhere on page on any frame.

回答1:

Remember a frame is a completely new HTML page with a whole separate DOM, so jQuery doesn't include it in your bindings.

So you will need to bind to those documents also:

function keyDownHandler(e) {
    if(e.keyCode==27){
        alert("escape pressed");
        e.preventDefault();
    }
}

for (var id in window.parent.frames)
    $(window.parent.frames[id].document).keydown(keyDownHandler);
$(document).keydown(keyDownHandler);

If the above doesn't work for you because of the id:

for (var i = 0; i < window.parent.frames.length; i ++) {
   var frame = window.parent.frames[i].document;
   frame.addEventListener("keydown",keyDownHandler, true);
}

If you want to reference all frames, from the top level

for (var i = 0; i < top.window.frames.length; i ++) {
   var frame = top.window.frames[i].document;
   frame.addEventListener("keydown",keyDownHandler, true);
}


回答2:

You can also try this:

Write your code in .js file and include file in all frames. This way you have to write function only onces and you can call it in all frames.

Hope this hepls.