js阻止瀏覽器的默認行爲以及中止事件冒泡(用JQuery實現回車提交)

在前端開發工做中,因爲瀏覽器兼容性等問題,咱們會常常用到「中止事件冒泡」和「阻止瀏覽器默認行爲」。javascript

1.阻止瀏覽器的默認行爲html

[java]  view plaincopy
  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.中止事件冒泡前端

[java]  view plaincopy
  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. }  

  

具體應用實例:寫好的一個項目,今天交給用戶使用,返回了一大堆問題,其中有一個很精典:java

一個頁面,有一個表單,用來提交表單的按鈕是個button,用jquery來響應這個按鈕的點擊動做,經過post提交,供用戶輸入的是一個文本框,用戶輸入完要填的東西以後,直接按回車鍵,就至關於按了那個button,剛開始沒注意這個問題,一按回車,就跳轉到了另一個頁面,查了不少資料,才發現要阻止瀏覽器的默認行爲,,由於SUBMIT的默認行爲是提交表單,那麼你的JS就不會執行了。因此先取消默認行爲。而後執行你的JQ來提交。具體的我也說不清楚,只知道若文本框的type="submit",直接點擊按鈕的時候就會跳到另一個頁面,若type="button",則點擊按鈕的時候不會出現這樣的狀況,可按回車鍵的時候會跳到另一個頁面,解決方法,看下面代碼:jquery

jsp代碼:web

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

 

js代碼:瀏覽器

[java]  view plaincopy
  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鍵,會跳到上一個瀏覽器的歷史記錄頁面;app

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

 

 

[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鍵代替回車鍵。代碼以下:

[java]  view plaincopy
  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>  

具體用法試例:

[java]  view plaincopy
  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="width: 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>  
相關文章
相關標籤/搜索