• js阻止浏览器的默认行为以及停止事件冒泡(用JQuery实现回车提交)


    在前端开发工作中,由于浏览器兼容性等问题,我们会经常用到“停止事件冒泡”和“阻止浏览器默认行为”。

    1.阻止浏览器的默认行为

    1. function stopDefault(e) {  
    2.         //如果提供了事件对象,则这是一个非IE浏览器   
    3.         if(e && e.preventDefault) {  
    4.           //阻止默认浏览器动作(W3C)  
    5.           e.preventDefault();  
    6.         } else {  
    7.           //IE中阻止函数器默认动作的方式   
    8.           window.event.returnValue = false;   
    9.         }  
    10.         return false;  
    11.     }  

    2.停止事件冒泡

    1. function stopBubble(e) {  
    2.     //如果提供了事件对象,则这是一个非IE浏览器  
    3.     if(e && e.stopPropagation) {  
    4.     //因此它支持W3C的stopPropagation()方法  
    5.     e.stopPropagation();   
    6.     } else {  
    7.     //否则,我们需要使用IE的方式来取消事件冒泡   
    8.     window.event.cancelBubble = true;  
    9.     }  
    10.     return false;   
    11. }  

      

    具体应用实例:写好的一个项目,今天交给用户使用,返回了一大堆问题,其中有一个很精典:

    一个页面,有一个表单,用来提交表单的按钮是个button,用jquery来响应这个按钮的点击动作,通过post提交,供用户输入的是一个文本框,用户输入完要填的东西之后,直接按回车键,就相当于按了那个button,刚开始没注意这个问题,一按回车,就跳转到了另外一个页面,查了很多资料,才发现要阻止浏览器的默认行为,,因为SUBMIT的默认行为是提交表单,那么你的JS就不会执行了。所以先取消默认行为。然后执行你的JQ来提交。具体的我也说不清楚,只知道若文本框的type="submit",直接点击按钮的时候就会跳到另外一个页面,若type="button",则点击按钮的时候不会出现这样的情况,可按回车键的时候会跳到另外一个页面,解决方法,看下面代码:

    jsp代码:

    1. <input type="text" name="appGrpName_s" id="appGrpName_s" onkeydown="enter_down(this.form, event);"/>  

    js代码:

    1. <script type="text/javascript">  
    2.     function enter_down(form, event) {   
    3.       if(event.keyCode== "13") {  
    4.           stopDefault(event);  
    5.           submitForm(form,'actionDiv');  
    6.       }  
    7.     }  
    8.       
    9.     function stopDefault(e) {  
    10.         //如果提供了事件对象,则这是一个非IE浏览器   
    11.         if(e && e.preventDefault) {  
    12.           //阻止默认浏览器动作(W3C)  
    13.           e.preventDefault();  
    14.         } else {  
    15.           //IE中阻止函数器默认动作的方式   
    16.           window.event.returnValue = false;   
    17.         }  
    18.         return false;  
    19.     }  
    20. </script>  

    通过上面的代码就可以实现按回车的时候相当于点击“提交”按钮。且上面的代码兼容IE、FF浏览器。

    有时候遇到需要屏蔽浏览器的一些快捷键行为时,比如说:ff下按Backspace键,会跳到上一个浏览器的历史记录页面;

    注意要在onkeydown事件中调用stopDefault(event)函数,在onkeyup事件中调用是不成功的。

    [javascript] view plaincopy
    1. <span style="color:#339933"><</span>a onclick<span style="color:#339933">=</span><span style="color:#3366cc">"toggleFriendFuncList(event, '6708062', 'he');"</span><span style="color:#339933">></</span>a<span style="color:#339933">></span>  

    由于href是空值,如果不阻止浏览器的默认行为,产生的效果就是刷新页面。 现在我们需要做的就是阻止href的链接事件,而去执行onclick事件。 老的处理方式:

    [javascript] view plaincopy
    1. <span style="color:#339933"><</span>a onclick<span style="color:#339933">=</span><span style="color:#3366cc">"toggleFriendFuncList(event, '6708062', 'he');"</span> href<span style="color:#339933">=</span><span style="color:#3366cc">"javascript:void(0);"</span><span style="color:#339933">></</span>a<span style="color:#339933">></span>  

    jquery的写法: 1)return false :In event handler ,prevents default behavior and event bubbing 。 return false 在事件的处理中,可以阻止默认事件和冒泡事件。 2)event.preventDefault():In event handler ,prevent default event (allows bubbling) 。 event.preventDefault()在事件的处理中,可以阻止默认事件但是允许冒泡事件的发生。 3)event.stopPropagation():In event handler ,prevent bubbling (allows default behavior). event.stopPropagation()在事件的处理中,可以阻止冒泡但是允许默认事件的发生

    prototype的写法: Event.stop(event) 用法介绍: 事件发生后,浏览器通常首先触发事件发生元素上的事件处理程序,然后是它的父元素,父元素的父元素……依此类推, 直到文档的根元素为止。这被称为 事件冒泡,是事件传播的最常见的方式。当处理好一个事件后, 你可能想要停止事件的传播,不希望它继续冒泡。 当你的程序有机会处理事件时,如果这个事件具有 默认行为,同时浏览器也会处理它。例如,点击导航链接、 将表单提交到服务器、在一个单行文本框中按下回车键等等。如果对这些事件你定义了自己的处理方式, 可能会非常希望阻止相关的默认行为。

    但是,有时候还是不能解决相应的问题,明明已经调用了阻止浏览器默认行为的方法,可在按回车的时候还是会调用默认行为,最终也没有找到问题所在,只好把回车键禁用了,实际上是用Tab键代替回车键。代码如下:

    1. <script language="javascript" event="onkeydown" for="document">  
    2.   //若为回车键  
    3.   if ( event.keyCode == 13 ) {  
    4.     //改成Tab键,这样每次按回车都起到了Tab的功效,光标跳到下一个对象  
    5.     event.keyCode = 9;  
    6.    }  
    7. </script>  
    8.   
    9. <script language="javascript" type="text/javascript">   
    10.   //禁用Enter键表单自动提交    
    11.       document.onkeydown = function(event) {    
    12.           var target, code, tag;    
    13.         if (!event) {    
    14.             event = window.event; //针对ie浏览器    
    15.             target = event.srcElement;    
    16.             code = event.keyCode;    
    17.             if (code == 13) {    
    18.                  tag = target.tagName;    
    19.                  if (tag == "TEXTAREA") { return true; }    
    20.                  else { return false; }    
    21.              }    
    22.          }    
    23.          else {    
    24.              target = event.target; //针对遵循w3c标准的浏览器,如Firefox    
    25.              code = event.keyCode;    
    26.             if (code == 13) {    
    27.                  tag = target.tagName;    
    28.                  if (tag == "INPUT") { return false; }    
    29.                  else { return true; }     
    30.             }    
    31.        }    
    32.      };    
    33. </script>  

    具体用法试例:

    1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    2. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
    3. <%@ include file="/pages/common/global.jsp"%>  
    4. <html>  
    5. <head>  
    6.     <title>高德软件</title>  
    7.     <meta http-equiv="pragma" content="no-cache">  
    8.     <meta http-equiv="cache-control" content="no-cache">  
    9.     <meta http-equiv="expires" content="0">  
    10.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
    11. <script>  
    12.     function gotoPage(currentPage,form) {  
    13.         goto_Page(currentPage,form,"actionDiv");  
    14.     }  
    15.     function addAppGrp(){  
    16.         $("#actionDiv").load("${contextPath }/pages/manage/business/add.jsp");  
    17.         $("#chance_search_div").hide();  
    18.     }  
    19.     function modifyAppGrp(idName){  
    20.         var id=encodeURIComponent(idName);  
    21.         var url = contextName + "/appGrpAction.do?method=addAppGrp&appGrpName="+id;  
    22.         retrieveURL(url,'actionDiv');  
    23.         $("#chance_search_div").hide();  
    24.     }  
    25.     function savebusiness(thisForm){  
    26.         var name = $("#appGrpName").val();  
    27.         if(name.trim()==""){  
    28.             alert("分组名称不能为空。");  
    29.             return;  
    30.         }  
    31.         submitForm(thisForm,null,afterSave);  
    32.         return ;  
    33.     }  
    34.     function afterSave(content){  
    35.         if(content!=null&&content!=""){  
    36.             var arr = content.split(",");  
    37.             if(arr[0]=="true"){  
    38.                 $("#chance_search_div").show();  
    39.                 //当前结点  
    40.                 var itemId = "0::" + $("#appGrpName").val();  
    41.                 //父结点,因为只有添加根应用分组时才会执行这个方法,所以父结点统一为-1  
    42.                 var parentId = -1;  
    43.                 //当前结点显示名称  
    44.                 var itemText = $("#appGrpName").val();  
    45.                 //添加新结点  
    46.                 tree.insertNewChild(parentId, itemId, itemText, doOnClick, 'myfolderClosed.gif' ,'myfolderOpen.gif','myfolderClosed.gif');  
    47.                 retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv");  
    48.                 return;  
    49.             }  
    50.             alert(arr[1]);  
    51.             return;  
    52.         }  
    53.         alert("保存失败");  
    54.         return;  
    55.     }  
    56.     function deleteBusiness(thisForm,idName){  
    57.         if(confirm("确认要删除么?")){  
    58.             var id=encodeURIComponent(idName);  
    59.             retrieveURL("${contextPath}/appGrpAction.do?method=deleteAppGrp&appGrpName=" + id,null,null,function(content){  
    60.                 if(content!=null&&content!=""){  
    61.                     var arr = content.split(",");  
    62.                     if(arr.length==3&&arr[2]=='y'){  
    63.                         var msg = "该应用组下有应用,要强制删除么?";  
    64.                         if(confirm(msg)){  
    65.                             retrieveURL("${contextPath}/appGrpAction.do?method=forceDelAppGrp&appGrpName="+id,null,null,afterForceDel);  
    66.                         }  
    67.                         return;  
    68.                     }  
    69.                     if(arr.length==2){  
    70.                         if(arr[0]=="true"){  
    71.                             //当前结点  
    72.                             itemId = "0::" + idName;  
    73.                             tree.deleteItem(itemId);  
    74.                             retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv");  
    75.                             return;  
    76.                         }  
    77.                         alert(arr[1]);  
    78.                     }  
    79.                     return;  
    80.                 }  
    81.                 alert("删除失败");  
    82.                 return;  
    83.             });  
    84.             return ;  
    85.         }  
    86.     }  
    87.     function afterForceDel(){  
    88.         if(content!=null&&content!=""){  
    89.             var arr = content.split(",");  
    90.             if(arr[0]=="true"){  
    91.                 monitorTree();  
    92.                 retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv");  
    93.                 return;  
    94.             }  
    95.             alert(arr[1]);  
    96.             return;  
    97.         }  
    98.         alert("保存失败");  
    99.         return;  
    100.     }  
    101.       
    102.       
    103.     function enter_down(form, event) {   
    104.       if(event.keyCode== "13") {  
    105.           stopDefault(event);  
    106.           submitForm(form,'actionDiv');  
    107.       }  
    108.     }  
    109.       
    110.     function stopDefault(e) {  
    111.         //如果提供了事件对象,则这是一个非IE浏览器   
    112.         if(e && e.preventDefault) {  
    113.           //阻止默认浏览器动作(W3C)  
    114.           e.preventDefault();  
    115.         } else {  
    116.           //IE中阻止函数器默认动作的方式   
    117.           window.event.returnValue = false;   
    118.         }  
    119.         return false;  
    120.     }  
    121. </script>  
    122. </head>  
    123. <body>  
    124.     <table style=" 100%; align: center;">  
    125.         <tr>  
    126.             <td style="text-align:left;">  
    127.                 <div id="chance_search_div">  
    128.                 <html:form action="appGrpAction.do?method=appGrpList">  
    129.                 <table class="form_t">  
    130.                     <tr>  
    131.                         <th class="tablelogo">    查询  
    132.                             <input type="hidden" name="hidden_s" value="1" />  
    133.                         </th>  
    134.                     </tr>  
    135.                     <tr>  
    136.                         <td style="text-align: left; padding-left: 50px;">  
    137.                             <br />  
    138.                             名称   
    139.                             <input type="text" name="appGrpName_s" id="appGrpName_s"  
    140.                                         onblur="javascript:isSpecialChar(this);" onkeydown="enter_down(this.form, event);"/>  
    141.                                                    
    142.                             <input type="button" class="button4C" value="查 询"  
    143.                                             onclick="javascript:submitForm(this.form,'actionDiv');" />    
    144.                             <input type="button" value="添  加" class="button4C" onclick="javascript:addAppGrp();"/>  
    145.           
    146.                             <br />   
    147.                         </td>  
    148.                     </tr>  
    149.                  </table>  
    150.                 </html:form>  
    151.                   
    152.                 </div>  
    153.                 <div id="actionDiv"></div>  
    154.             </td>  
    155.         </tr>  
    156.     </table>  
    157.     <script><!--  
    158.         $("#actionDiv").load("${contextPath }/appGrpAction.do?method=appGrpList&random=" + Math.random());  
    159.     --></script>     
    160. </body>  
    161. </html>  
  • 相关阅读:
    查漏补缺:2020年搞定SpringCloud面试(含答案和思维导图)
    如何在半小时搭建一个简单的日志分析平台?
    Flutter | 状态管理特别篇——Provide
    线程池是怎样工作的
    神奇的 SQL 之 联表细节 → MySQL JOIN 的执行过程
    github设置添加ssh
    pytorch中torch.cat(),torch.chunk(),torch.split()函数的使用方法
    八年以后,我选择了创业
    vue源码解读(一)Observer/Dep/Watcher是如何实现数据绑定的
    Ubuntu18.04安装Pytorch
  • 原文地址:https://www.cnblogs.com/ranzige/p/4045655.html
Copyright © 2020-2023  润新知