Bootstrap 模態對話框只加載一次 remote 數據的解決辦法

1. Bootstrap 模態對話框和簡單使用

<div id="myModal" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">x</button>
        <h3>對話框標題</h3>
    </div>
    <div class="modal-body">
        <p>對話框主體</p>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">取消</a>
        <a href="#" class="btn btn-primary" data-dismiss="modal">肯定</a>
    </div>
</div>

顯示效果與下圖類似:javascript

能夠使用按鈕或連接直接調用模態對話框,這是簡單的用法:css

<button type="button" data-toggle="modal" data-target="#myModal">打開對話框</button>
<a href="#myModal" role="button" class="btn" data-toggle="modal">打開對話框</button>

這樣只能把靜態內容在對話框中顯示出來,使用對話框的 remote 選項能夠實現更強大的效果。html

2. 使用 remote 選項讓模態對話框加載頁面到 .modal-body 中

有兩種方法,一種是使用連接,另外一種就是使用腳本。java

2.1 使用連接

<a href="page.jsp" data-toggle="modal" data-target="#myModal">打開對話框</a>

當點擊此連接時,page.jsp 的內容會被加載到對話框的 .modal-body 中,隨即顯示對話框。bootstrap

2.2 使用腳本

$("#myModal").modal({
    remote: "page.jsp"
});

這段腳本的效果和使用連接是同樣的,當這段腳本執行後,page.jsp 的內容會被加載到對話框的 .modal-body 中,隨即顯示對話框。服務器

這兩種方法的背後,都是 Bootstrap 調用了 jQuery 的 load() 方法,從服務器端加載了 page.jsp 頁面。但這個加載只會發生一次,後面無論你點擊幾回連接,或者執行幾回腳本,哪怕改變傳遞給 remote 選項的值,對話框都不會從新加載頁面,這真是個讓人頭疼的事情。不過問題仍是可以解決的。jsp

3. 移除數據,讓對話框可以在每次打開時從新加載頁面

在搜索並查閱了相關文檔後,發如今對話框的 hidden 事件裏寫上一條語句就能夠了:ide

$("#myModal").on("hidden", function() {
    $(this).removeData("modal");
});

也能夠在每次打開對話框以前移除數據,效果是同樣的。this

注:上面的代碼基於 Bootstrap v2,若是使用 Bootstrape v3,模態對話框的 HTML 和事件的寫法有一些不一樣,例如對於上面的 hidden 事件,要寫成:spa

$("#myModal").on("hidden.bs.modal", function() {
    $(this).removeData("bs.modal");
});

參考文檔

相關文章
相關標籤/搜索