2011-08-11 113 views
5

我一直試圖理解甚至冒泡,並且我不完全相信它。我開始閱讀它,以便當用戶在我的網站上離開一個頁面時,如果他們已經開始向表單中輸入數據(與StackOverflow類似的方式),我可以提醒用戶。瞭解javascript中的事件冒泡

下面的代碼似乎工作的跨瀏覽器:

var entereddata = false; 

$(document).ready(function() 
{ 
    $('#contactform').bind('keypress',function(e) { 
      if((e.which > 96 && e.which < 123) || (e.which > 47 && e.which < 58)) { 
        entereddata = true; 
        //alert(e.which); 
      } 
    }); 
}); 

function confirmLeave(e, d) 
{ 
    if(!e) e = window.event;//window.event; 
    if(!d) d = entereddata; 

    var confirmationMessage = 'It appears you have started to enter information into the contact form, but have not yet submitted it'; 

    if(!d) 
    { 
      e.cancelBubble = true; 
    } else 
    { 
      return confirmationMessage; 
    } 
} 

window.onbeforeunload=confirmLeave; 

然而,當我點擊的形式,我不想提交按鈕,這也被調用。我已經嘗試了各種增加的代碼,如添加:

if($('#submit').click()){ 
    submitted=true; 
} else { 
    submitted=false; 
} 

,然後如果(!d)到如果需要變更(!d & &提交== false)來主代碼;然而,這個(以及試圖只在沒有點擊提交按鈕時才觸發頁面的其他任何組合)都不起作用,當我單擊提交按鈕時警告或者仍然顯示,或者在顯示時沒有顯示警告點擊任何東西!

這可能歸結爲事實我不明白的事件冒泡過程 - 我不知道爲什麼我需要e.cancelBubble = true;在我擁有它的地方。

所以,我的2個主要問題有:

  • 我該如何檢查,如果被點擊提交按鈕,只顯示警告如果沒有點擊
  • 和理解eventBubbling;例如:如果enteredData爲true,那麼我不會影響冒泡過程。我可以做?如果enteredData爲false,我應該有e.cancelBubble = false,如果enteredData爲true,e.cancelBubble = true?關閉頁面時,設置e.cancelBubble的值實際上具有什麼作用?

我是否也正確認爲我根本不需要事件e.stopProgagation ,因爲firefox支持事件冒泡?

對於這篇長文章的道歉,並且預先感謝任何人能夠給予的幫助。

謝謝, 克里斯

回答

0

關於有這樣的代碼是什麼?

$('#submit').click(function() { 
    entereddata = false; 
}); 

這應該confirmLeave之前運行的實際表單提交,即之前被調用,所以降旗應該做的伎倆。

0

嘗試刪除onbeforeunload「監聽器」:

$('#submit').click(function() { 
    window.onbeforeunload=null; 
}); 

我不認爲你需要擔心在這個例子中冒泡......

返回NULL,如果你想在瀏覽器中前進不問用戶,或者如果您希望瀏覽器顯示一個警告,詢問用戶是否希望繼續前進或不返回一個字符串...

function confirmLeave(e) { 
    e = e || window.event;//window.event; 

    var confirmationMessage = 'It appears you have started to enter information into the  contact form, but have not yet submitted it'; 

    if(entereddata) { 
      return confirmationMessage; 
    } else { 
      return null; 
    } 
} 

起泡和傳播僅適用於事件」應該通知它的孩子或它的父母,並據我所知。onbeforeunload是一個不會被傳播的全局事件。

0

無關的冒泡,但是你可以繞過檢測是否按鍵和檢查表單數據,而不是:

function hasNonemptyTextInputs() { 
    var textInputs = $('#contactform :input').filter(':text, textarea'); 

    // Check for any field with a nonempty value 
    // .is() returns true iff the function returns true on any element 
    return textInputs.is(function() { 
     return $(this).val().length > 0; 
    }); 
}