在前端開發工作中,由於瀏覽器兼容性等問題,我們會經常用到“停止事件冒泡”和“阻止瀏覽器默認行為”。
1.阻止瀏覽器的默認行為
- function stopDefault(e) {
- //如果提供了事件對象,則這是一個非IE瀏覽器
- if(e && e.preventDefault) {
- //阻止默認瀏覽器動作(W3C)
- e.preventDefault();
- } else {
- //IE中阻止函數器默認動作的方式
- window.event.returnValue = false;
- }
- return false;
- }
2.停止事件冒泡
- function stopBubble(e) {
- //如果提供了事件對象,則這是一個非IE瀏覽器
- if(e && e.stopPropagation) {
- //因此它支持W3C的stopPropagation()方法
- e.stopPropagation();
- } else {
- //否則,我們需要使用IE的方式來取消事件冒泡
- window.event.cancelBubble = true;
- }
- return false;
- }
具體應用實例:寫好的一個項目,今天交給用戶使用,返回了一大堆問題,其中有一個很精典:
一個頁面,有一個表單,用來提交表單的按鈕是個button,用jquery來響應這個按鈕的點擊動作,通過post提交,供用戶輸入的是一個文本框,用戶輸入完要填的東西之后,直接按回車鍵,就相當於按了那個button,剛開始沒注意這個問題,一按回車,就跳轉到了另外一個頁面,查了很多資料,才發現要阻止瀏覽器的默認行為,,因為SUBMIT的默認行為是提交表單,那么你的JS就不會執行了。所以先取消默認行為。然后執行你的JQ來提交。具體的我也說不清楚,只知道若文本框的type="submit",直接點擊按鈕的時候就會跳到另外一個頁面,若type="button",則點擊按鈕的時候不會出現這樣的情況,可按回車鍵的時候會跳到另外一個頁面,解決方法,看下面代碼:
jsp代碼:
- <input type="text" name="appGrpName_s" id="appGrpName_s" onkeydown="enter_down(this.form, event);"/>
js代碼:
- <script type="text/javascript">
- function enter_down(form, event) {
- if(event.keyCode== "13") {
- stopDefault(event);
- submitForm(form,'actionDiv');
- }
- }
- function stopDefault(e) {
- //如果提供了事件對象,則這是一個非IE瀏覽器
- if(e && e.preventDefault) {
- //阻止默認瀏覽器動作(W3C)
- e.preventDefault();
- } else {
- //IE中阻止函數器默認動作的方式
- window.event.returnValue = false;
- }
- return false;
- }
- </script>
通過上面的代碼就可以實現按回車的時候相當於點擊“提交”按鈕。且上面的代碼兼容IE、FF瀏覽器。
有時候遇到需要屏蔽瀏覽器的一些快捷鍵行為時,比如說:ff下按Backspace鍵,會跳到上一個瀏覽器的歷史記錄頁面;
注意要在onkeydown事件中調用stopDefault(event)函數,在onkeyup事件中調用是不成功的。
- <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事件。 老的處理方式:
- <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鍵代替回車鍵。代碼如下:
- <script language="javascript" event="onkeydown" for="document">
- //若為回車鍵
- if ( event.keyCode == 13 ) {
- //改成Tab鍵,這樣每次按回車都起到了Tab的功效,光標跳到下一個對象
- event.keyCode = 9;
- }
- </script>
- <script language="javascript" type="text/javascript">
- //禁用Enter鍵表單自動提交
- document.onkeydown = function(event) {
- var target, code, tag;
- if (!event) {
- event = window.event; //針對ie瀏覽器
- target = event.srcElement;
- code = event.keyCode;
- if (code == 13) {
- tag = target.tagName;
- if (tag == "TEXTAREA") { return true; }
- else { return false; }
- }
- }
- else {
- target = event.target; //針對遵循w3c標准的瀏覽器,如Firefox
- code = event.keyCode;
- if (code == 13) {
- tag = target.tagName;
- if (tag == "INPUT") { return false; }
- else { return true; }
- }
- }
- };
- </script>
具體用法試例:
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ include file="/pages/common/global.jsp"%>
- <html>
- <head>
- <title>高德軟件</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
- <script>
- function gotoPage(currentPage,form) {
- goto_Page(currentPage,form,"actionDiv");
- }
- function addAppGrp(){
- $("#actionDiv").load("${contextPath }/pages/manage/business/add.jsp");
- $("#chance_search_div").hide();
- }
- function modifyAppGrp(idName){
- var id=encodeURIComponent(idName);
- var url = contextName + "/appGrpAction.do?method=addAppGrp&appGrpName="+id;
- retrieveURL(url,'actionDiv');
- $("#chance_search_div").hide();
- }
- function savebusiness(thisForm){
- var name = $("#appGrpName").val();
- if(name.trim()==""){
- alert("分組名稱不能為空。");
- return;
- }
- submitForm(thisForm,null,afterSave);
- return ;
- }
- function afterSave(content){
- if(content!=null&&content!=""){
- var arr = content.split(",");
- if(arr[0]=="true"){
- $("#chance_search_div").show();
- //當前結點
- var itemId = "0::" + $("#appGrpName").val();
- //父結點,因為只有添加根應用分組時才會執行這個方法,所以父結點統一為-1
- var parentId = -1;
- //當前結點顯示名稱
- var itemText = $("#appGrpName").val();
- //添加新結點
- tree.insertNewChild(parentId, itemId, itemText, doOnClick, 'myfolderClosed.gif' ,'myfolderOpen.gif','myfolderClosed.gif');
- retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv");
- return;
- }
- alert(arr[1]);
- return;
- }
- alert("保存失敗");
- return;
- }
- function deleteBusiness(thisForm,idName){
- if(confirm("確認要刪除么?")){
- var id=encodeURIComponent(idName);
- retrieveURL("${contextPath}/appGrpAction.do?method=deleteAppGrp&appGrpName=" + id,null,null,function(content){
- if(content!=null&&content!=""){
- var arr = content.split(",");
- if(arr.length==3&&arr[2]=='y'){
- var msg = "該應用組下有應用,要強制刪除么?";
- if(confirm(msg)){
- retrieveURL("${contextPath}/appGrpAction.do?method=forceDelAppGrp&appGrpName="+id,null,null,afterForceDel);
- }
- return;
- }
- if(arr.length==2){
- if(arr[0]=="true"){
- //當前結點
- itemId = "0::" + idName;
- tree.deleteItem(itemId);
- retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv");
- return;
- }
- alert(arr[1]);
- }
- return;
- }
- alert("刪除失敗");
- return;
- });
- return ;
- }
- }
- function afterForceDel(){
- if(content!=null&&content!=""){
- var arr = content.split(",");
- if(arr[0]=="true"){
- monitorTree();
- retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv");
- return;
- }
- alert(arr[1]);
- return;
- }
- alert("保存失敗");
- return;
- }
- function enter_down(form, event) {
- if(event.keyCode== "13") {
- stopDefault(event);
- submitForm(form,'actionDiv');
- }
- }
- function stopDefault(e) {
- //如果提供了事件對象,則這是一個非IE瀏覽器
- if(e && e.preventDefault) {
- //阻止默認瀏覽器動作(W3C)
- e.preventDefault();
- } else {
- //IE中阻止函數器默認動作的方式
- window.event.returnValue = false;
- }
- return false;
- }
- </script>
- </head>
- <body>
- <table style="width: 100%; align: center;">
- <tr>
- <td style="text-align:left;">
- <div id="chance_search_div">
- <html:form action="appGrpAction.do?method=appGrpList">
- <table class="form_t">
- <tr>
- <th class="tablelogo"> 查詢
- <input type="hidden" name="hidden_s" value="1" />
- </th>
- </tr>
- <tr>
- <td style="text-align: left; padding-left: 50px;">
- <br />
- 名稱
- <input type="text" name="appGrpName_s" id="appGrpName_s"
- onblur="javascript:isSpecialChar(this);" onkeydown="enter_down(this.form, event);"/>
- <input type="button" class="button4C" value="查 詢"
- onclick="javascript:submitForm(this.form,'actionDiv');" />
- <input type="button" value="添 加" class="button4C" onclick="javascript:addAppGrp();"/>
- <br />
- </td>
- </tr>
- </table>
- </html:form>
- </div>
- <div id="actionDiv"></div>
- </td>
- </tr>
- </table>
- <script><!--
- $("#actionDiv").load("${contextPath }/appGrpAction.do?method=appGrpList&random=" + Math.random());
- --></script>
- </body>
- </html>