【问题标题】:JQuery- hotkeys and windows prompt issueJQuery-热键和窗口提示问题
【发布时间】:2010-11-10 04:55:33
【问题描述】:

参考这个link 我尝试实现这个强大的工具并面临一些问题。

每次点击Ctrl S,都会弹出一个窗口提示我是否要保存我的testing.html。

我想忽略 windows 提示。

我想要的很简单:

  1. 当人们点击保存按钮/使用键盘快捷键ctrl s

  2. 脚本需要做Create()检查

  3. 如果为真则继续提交表单,如果为假则停止提醒Please enter question,重新关注txtQuestion,不再进行任何操作。

以下是完整的源代码供参考: 进入

   <html>
   <head>
       <style>
           * {font-family: Helvetica, Verdana, Arial; font-size:0.95em}
           .eventNotifier{width: 100px; float: left; color:navy; 
                 border: dotted 1px navy; padding: 4px; background-color:white; 
                 margin:3px}
           .dirty{border: solid 1px #0ca2ff; color:white; 
                  background-color:#0ca2ff}
       </style>
   
       <script src="jquery-1.3.2.min.js"></script>
       <script src="jquery.hotkeys-0.7.9.min.js"></script>
       <script type="text/javascript">
           $(document).ready(function() {

//weird- I found the alert Ctrl+S to appear twice.. ???
$(window).keypress(function(event) {
 if ((event.which == 115 && event.ctrlKey)){
     alert("Ctrl+S pressed");
     event.preventDefault();
 }
});

               jQuery(document).bind('keydown', 'Ctrl+s',
                      function(evt){ Create(); return false; });
               //jQuery(document).bind('keydown', 'Ctrl+s',
                     //function (evt){jQuery('#_Ctrl_s'); return false; });
           });
       
           function Create()
           {
               var f = document.frm
       
               if (f.txtQuestion.value.length == 0)
               {
                   alert('Please enter Question.')
                   f.txtQuestion.focus()
                   return false
               }
               f.submit()
           }
   
       </script>
   </head>
   <body> 
       <form name="frm" method=post action="" >
         <div id="_Ctrl_s" class="eventNotifier">Ctrl+s</div>
         <input type=text name="txtQuestion" maxlength="255" 
                   class="field400" value="">
         <input type=button value="Save" name="BtnSave" onclick="Create()" 
                   class=text100>
       </form>
   </body>
   </html>

代码在这里

【问题讨论】:

    标签: javascript jquery windows hotkeys prompt


    【解决方案1】:

    为避免显示浏览器另存为对话框,您必须阻止默认事件操作,例如纯 jQuery:

    $(window).keypress(function(event) {
      if ((event.which == 115 && event.ctrlKey)){
          alert("Ctrl+S pressed");
          event.preventDefault();
      }
    });
    

    【讨论】:

    • hmm.. 有趣的是在演示站点上,我看不到任何 .preventDefault() 代码,但它仍然运行良好。
    【解决方案2】:

    您的代码 sn-p 没问题,但为了防止默认浏览器操作(如显示保存对话框),您必须捕获 KeyPress 事件(不是 KeyDown),当然 return false

    jQuery(document).bind('keypress', 'Ctrl+S',function (evt){ 
     //do job..
     return false
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2011-01-19
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多