2017-04-26 27 views
2

我有一個按鈕,屬性data-toggledata-target。這是完整的按鈕腳本:如何將這個html腳本應用於jQuery?

<button style="width:50%; float:left" type="button" class="btn btn-info" id="btn_report" data-toggle="modal" data-target="#myModal">Detail</button> 

此按鈕打開一個簡單的模式。模態也可以通過在模態框外單擊來關閉。不過,我想在使用jQuery的按鈕中有一些規則。

$('#btn_report').on('click',function(e){ 
    var dataSend = "some_data"; 
    $.ajax({ 
     type: "POST", 
     url: "some_function", 
     cache: false, 
     dataType : "json", 
     data: dataSend, 
     success: function(response) { 
      if(response){ 
       $('#myModal').show(); 
      }else{ 
       alert("There are no data to be displayed"); return false; 
      } 
     } 
    }) 
}); 

隨着data-toggledata-target,進行模態總是每當我點擊按鈕打開。如果我刪除data-toggledata-target並添加$('#myModal').show();,則不顯示模式。

我想要做的是打開模式,如果有數據從ajax返回。如果沒有,警報會被解僱。

的模式很簡單這樣的:

<div class="modal fade" id="myModal" role="dialog"> 
    <div class="modal-dialog"> 
    <!-- Modal content--> 
    <div class="modal-content" id="printMe"> 
     <div class="modal-body"> Congrats, you have your data </div> 
    </div> 
    </div> 
</div> 
+0

$( '#myModal')模態( '秀')。更改代碼, –

回答

2

由於您使用的是引導莫代爾你需要使用modal('open'),不show()。試試這個:

if (response) { 
    $('#myModal').modal('show'); 
} else { 
    alert("There are no data to be displayed"); 
} 

還要注意的是return是多餘的,因爲你不能從異步success處理函數中的任何回報。

+0

謝謝。 我已經改變它'打開'並從按鈕中移除'data-toggle =「modal」data-target =「#myModal」''。但是模式沒有顯示出來。爲什麼? – Shota

+0

問題中沒有足夠的信息來診斷,因爲這應該起作用。檢查控制檯是否有錯誤 –

+0

現在正在工作。但是,沒有幻燈片效果。如何添加它? – Shota

0

在點擊監聽器添加event.stopPropagation()

$('#btn_report').on('click',function(e){ 
    event.stopPropagation(); 
    setTimeout(function() { 
     // ajax mock 
     $('#myModal').modal('show'); 
    }, 2000); 
}); 
+1

雖然這段代碼可以解決這個問題,[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers )真的有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

相關問題