2013-09-26 28 views
0

我試圖添加一個確認框到許多鏈接,按鈕或輸入,點擊事件。JQuery:添加一個確認處理程序綁定/開和觸發函數

我不能使用location.href,提交(),或其他特定的功能,因爲:

  • location.href,例如,將不會提交按鈕的工作,
  • 位置。例如,href不會觸發其他綁定處理程序。

所以我需要使用的是trigger()函數,它在理論上執行所有的處理程序和本地操作。 「困難」部分是執行所有處理程序,除了彈出確認框的處理程序。

這裏是我的代碼:

$('a, button, input[type="submit"]').each(function() { 

    var oButton = $(this); 

    oButton.on('click.pending', function(oEvent) { 
     console.log('click !'); 
     oEvent.preventDefault(); 

     var oDialog = $('<div class="dialog-example">[Question] ?</div>').dialog({ 
      buttons: { 
       Cancel: function() { 
        console.log('cancelled !'); 
        // Nothing to do 
        oDialog.dialog('close'); 
       }, 
       Ok: function() { 
        console.log('confirmed !'); 
        // Trigger the rest of the handlers AND the native action, BUT not this one, so this dialog is not used 
        // Problem : nothing happens here 
        oButton.trigger('click.confirmed'); 
        oDialog.dialog('close'); 
       } 
      } 
     }); 
    }); 

}); 

提前感謝! ;)

+0

你可以創建一個小提琴嗎? –

+0

小提琴:http://jsfiddle.net/Chicna/EerEF/2/ – Chicna

+0

在這種情況下,爲了「清晰」的代碼,我使用這樣的東西:http://jsfiddle.net/EerEF/4/ (oops) –

回答

0

你應該嘗試:

oButton.off('click.pending').trigger('click').get(0).click(); 

DEMO

+0

不錯!但檢查只完成一次。我想你需要在代碼後重新啓動處理程序。 – Chicna

+0

點擊錨或提交應該將用戶重定向到新頁面或重新加載當前頁面,所以通常情況下,您不應該重新綁定事件。這就是說,你仍然可以使用引用的函數,並在事件發生後重新綁定它:http://jsfiddle.net/EHkGq/show/ –

+0

新的小提琴:http://jsfiddle.net/Chicna/gtR2j/2/ – Chicna

相關問題