基于Bootstrap模態(tài)對話框只加載一次 remote 數(shù)據(jù)的解決方法
摘要: 前端框架 Bootstrap 的模態(tài)對話框,可以使用 remote 選項指定一個 URL,這樣對話框在第一次彈出的時候就會自動從這個地址加載數(shù)據(jù)到 .modal-body 中,但是它只會加載一次,不過通過在事件中調(diào)用 removeData() 方法可以解決這個問題。
1. Bootstrap 模態(tài)對話框和簡單使用
<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="#" rel="external nofollow" rel="external nofollow" class="btn" data-dismiss="modal">取消</a>
<a href="#" rel="external nofollow" rel="external nofollow" class="btn btn-primary" data-dismiss="modal">確定</a>
</div>
</div>
顯示效果與下圖相似:

可以使用按鈕或鏈接直接調(diào)用模態(tài)對話框,這是簡單的用法:
<button type="button" data-toggle="modal" data-target="#myModal">打開對話框</button> <a href="#myModal" rel="external nofollow" role="button" class="btn" data-toggle="modal">打開對話框</button>
這樣只能把靜態(tài)內(nèi)容在對話框中顯示出來,使用對話框的 remote 選項可以實現(xiàn)更強大的效果。
2. 使用 remote 選項讓模態(tài)對話框加載頁面到 .modal-body 中
有兩種方法,一種是使用鏈接,另一種就是使用腳本。
2.1 使用鏈接
<a href="page.jsp" rel="external nofollow" data-toggle="modal" data-target="#myModal">打開對話框</a>
當點擊此鏈接時,page.jsp 的內(nèi)容會被加載到對話框的 .modal-body 中,隨即顯示對話框。
2.2 使用腳本
$("#myModal").modal({
remote: "page.jsp"
});
這段腳本的效果和使用鏈接是一樣的,當這段腳本執(zhí)行后,page.jsp 的內(nèi)容會被加載到對話框的 .modal-body 中,隨即顯示對話框。
這兩種方法的背后,都是 Bootstrap 調(diào)用了 jQuery 的 load() 方法,從服務(wù)器端加載了 page.jsp 頁面。但這個加載只會發(fā)生一次,后面不管你點擊幾次鏈接,或者執(zhí)行幾次腳本,哪怕改變傳遞給 remote 選項的值,對話框都不會重新加載頁面,這真是個讓人頭疼的事情。不過問題還是能夠解決的。
3. 移除數(shù)據(jù),讓對話框能夠在每次打開時重新加載頁面
在搜索并查閱了相關(guān)文檔后,發(fā)現(xiàn)在對話框的 hidden 事件里寫上一條語句就可以了:
$("#myModal").on("hidden", function() {
$(this).removeData("modal");
});
也可以在每次打開對話框之前移除數(shù)據(jù),效果是一樣的。
注:上面的代碼基于 Bootstrap v2,如果使用 Bootstrape v3,模態(tài)對話框的 HTML 和事件的寫法有一些不同,例如對于上面的 hidden 事件,要寫成:
$("#myModal").on("hidden.bs.modal", function() {
$(this).removeData("bs.modal");
});
以上這篇基于Bootstrap模態(tài)對話框只加載一次 remote 數(shù)據(jù)的解決方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Dropzone.js實現(xiàn)文件拖拽上傳功能(附源碼下載)
dropzone.js是重量輕的JavaScript庫,將HTML元素設(shè)置為一個降落區(qū),并通過Ajax文件被上傳到服務(wù)器。本文給大家詳細介紹Dropzone.js實現(xiàn)文件拖拽上傳功能,需要的朋友參考下吧2016-11-11
逐行分析鴻蒙系統(tǒng)的 JavaScript 框架(推薦)
鴻蒙系統(tǒng)使用 JavaScript 開發(fā) GUI 是一種類似于微信小程序、輕應(yīng)用的模式。這篇文章給大家?guī)砹酥鹦蟹治鲽櫭上到y(tǒng)的 JavaScript 框架的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2020-09-09
Vue elementUI實現(xiàn)免密登陸與號碼綁定功能
這篇文章主要介紹了Vue elementUI實現(xiàn)免密登陸與號碼綁定功能,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-11-11

