2012-08-13 66 views
11

好吧,我絕不是JavaScript專家,也許我仍然在思考桌面軟件開發方面的問題,但這正是我想要實現的:等待來自Javascript模式的「返回值」

  • 我使用Twitter Bootstrap's Modals
  • 在某些情況下,一個動作發生之前,我想用一個驗證它「你確定?」 (是/否)模態對話框。

問:

  • 應該採取什麼內在邏輯是什麼?

我的意思是:

  • 用戶點擊按鈕a(其最終執行actionA)
  • 我要啓動的模態,等待輸入(或者是2個按鈕的 - 是/否)和/或執行(或沒有)actionA

這是我的HTML代碼的模式(應的按鈕,在它之前通過一些常規的檢查 - 以某種方式 - 通過他們作用javascript例程?) - 還要注意,#confirmMessage將會變化。

<div class="modal fade hide" id="confirmAlert"> 
    <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal">x</button> 
     <h3 id="confirmTitle">Are you sure?</h3> 
    </div> 

    <div class="modal-body"> 
     <p id="confirmMessage">Body</p> 
    </div> 
    <div class="modal-footer"> 
     <a href="#" class="btn" data-dismiss="modal">Cancel</a> 
     <a href="#" class="btn btn-danger">Yes</a> 
    </div> 
</div> 

只是一個想法:

  • 寫像checkBeforeExec(message,functionToExec)
  • 設置#confirmMessage的信息,然後是HREF到javascript:functionToExec功能
  • 有道理?

我知道這聽起來有點混亂 - 但我根本不知道什麼是最的JavaScript友好的方式來做到這將是...

回答

10

我創建了一個對話管理器周圍模式與confirm助手功能,基本上做到這一點:

var callback = function(result) { 
    alert(result); 
}); // define your callback somewhere 

$('#confirmAlert').on('click', '.btn, .close', function() { 
    $(this).addClass('modal-result'); // mark which button was clicked 
}).on('hidden', function() { 
    var result = $(this).find('.modal-result').filter('.btn-danger').length > 0; // attempt to filter by what you consider the "YES" button; if it was clicked, result should be true. 

    callback(result); // invoke the callback with result 
}); 

此外,您應該使雙方的取消,是按鈕data-dismiss="modal"

Here's a fiddle, with a simple example of my dialog manager

請注意,如果您使用的是引導3,你應該添加一個處理程序的hidden.bs.modal事件,而不是hidden

+0

非常感謝!這非常有幫助!;-) – 2012-08-13 10:46:09

+0

'你應該使取消和是按鈕' - 如果你停止事件處理程序中的事件傳播,這可能不起作用。在這種情況下,單擊yes時使用'modal('hide')'。 – Medorator 2014-08-03 11:48:31

1

與jQuery你可以使用類似

$('.btn').click(function(){ 
    val=$(this).val() 
    if(val=='Yes'){ 
    //continue the processing 
    } 
})