回答

17

不要使用data-dismiss="modal",讓你的函數close(隱藏)您的模式:

<button type="button" class="btn btn-success btn-sm" onclick="do_save()">Save</button> 

function do_save() 
    { 
     if(Math.floor(Math.random() * 2)==1) 
     { 
      console.log('success'); 
      $('#myModal').modal('hide'); 
      return; 
     } 
     console.log('failure'); 
     return false; 
    } 
5

由於您使用jQuery的反正儘量不要有使用Javascript/jQuery的嵌入代碼

$('#buttonId').on('click', function() { 
    // either call do_save or embed the contents of do_save in here 
    var myDataIsValid = true; // change to call validator function 
    if (myDataIsValid) { 
    $('#myModal').modal('hide'); 
    } 
    return true; // value depends on whether you want stopPropagation or not. 
}); 

HTML:

<button id="buttonId" type="button" class="btn btn-success btn-sm">Save</button> 

作爲一種替代方法,您可以通過攔截'hide'事件並從中返回false來阻止關閉。

3

如果趕上從按鈕的點擊事件是這樣的:

 $('#buttonId').off('click').click(function(clickEvent){ 
     //enter code here 
    }); 

實際上,你可以防止你的模式的結束。爲此,根據您的情況,你會發現這兩個功能非常有用:

 clickEvent.preventDefault(); 
    clickEvent.stopPropagation(); 

如果我理解的這個網站(在德國) http://www.mediaevent.de/javascript/event-handler-default-verhindern.html 正確,preventDefault()方法停止立即默認動作(如跟隨一個鏈接)。然而,事件本身仍然會遍歷DOM,並且可以被各種事件監聽器「聽到」,其中之一是隱藏模式的事件監聽器。爲此,需要第二個功能,它可以阻止事件在DOM中的傳播。因此,隱藏監聽器無法聽到該窗口,窗口也不會關閉(隱藏)。因此,我建議實行像這樣的功能:

 $('#buttonId').off('click').click(function(clickEvent){ 
     //enter code here 
     var myDataIsValid = true; 
     // check if Data is valid => myDataIsValid = true or false 
     if(myDataIsValid){ 
     //do Stuff 
     }else{ 
     clickEvent.preventDefault(); 
     clickEvent.stopPropagation(); 
     //do other Stuff 
     } 
    }); 

在我的代碼,我只需要使用stopPropagation(),爲我的默認行爲是需要的,因此您可以單獨使用這兩種功能。

注意:此解決方案僅用Firefox瀏覽器進行測試