我正在构建一个Rails应用程序,我希望通过AJAX将Rails部分内容放入模态中。
在Twitter Bootstrap 2.3.2模式中,我通过文档阅读您可以使用远程密钥通过ajax加载内容。
http://getbootstrap.com/2.3.2/javascript.html#modals
但是,这只允许将内容注入.modal-body
,而不是动态构建整个模态。
有没有办法用JS动态构建整个模态,包括.modal-header
,.modal-footer
?
使用字符串执行此操作似乎非常笨重,如下所示:
partial = render_to_string(:partial => 'some-partial').gsub(%{"}, %{'}).gsub(/'/,"\\\\'").gsub("\n", "")
答案 0 :(得分:33)
<强>更新强>
自发布以来,我发现了一个优雅的bootstrap 3模态包装函数here,它不需要在html代码中添加div。
这是一个演示此问题的代码示例。要使用,只需在&lt; body&gt;中添加div即可。 (在bootstrap的&lt; div class =“container”&gt;中,例如:
<div id="idMyModal"></div>
然后您可以通过以下方式使用它:
var header = "This is my dynamic header";
var content = "This is my dynamic content";
var strSubmitFunc = "applyButtonFunc()";
var btnText = "Just do it!";
doModal('idMyModal', header, content, strSubmitFunc, btnText);
要关闭模态,请调用hideModal,也在下面定义:
function doModal(placementId, heading, formContent, strSubmitFunc, btnText)
{
var html = '<div id="modalWindow" class="modal hide fade in" style="display:none;">';
html += '<div class="modal-header">';
html += '<a class="close" data-dismiss="modal">×</a>';
html += '<h4>'+heading+'</h4>'
html += '</div>';
html += '<div class="modal-body">';
html += '<p>';
html += formContent;
html += '</div>';
html += '<div class="modal-footer">';
if (btnText!='') {
html += '<span class="btn btn-success"';
html += ' onClick="'+strSubmitFunc+'">'+btnText;
html += '</span>';
}
html += '<span class="btn" data-dismiss="modal">';
html += 'Close';
html += '</span>'; // close button
html += '</div>'; // footer
html += '</div>'; // modalWindow
$("#"+placementId).html(html);
$("#modalWindow").modal();
}
function hideModal()
{
// Using a very general selector - this is because $('#modalDiv').hide
// will remove the modal window but not the mask
$('.modal.in').modal('hide');
}
答案 1 :(得分:27)
<强>更新强>
我最近偶然发现了bootbox.js,它是一个专门用于动态创建引导模式并响应用户与它们交互的整个库。虽然与下面的方法不同,但bootbox接受回调而不是函数名称。我还没有亲自使用它,因为我无法证明26kb库基本上可以完成下面的功能。但我认为有人可能觉得它很有用。
2016年8月17日更新
我现在几乎每个需要动态模态的项目都使用bootbox。工作得很好我强烈推荐它。
更新10/1/2018
Bootbox尚未正式支持bootstrap 4,但有一个bootbox v5.x分支,他们正在使用bootstrap 4支持。根据{{3}}和5.0.0 roadmap票据,听起来分支已准备就绪,但他们还没有发布它。但是有一些关于如何使用它的说明。 免责声明:我还没有习惯v5.x分支,也无法保证其完整性。
更新3/25/2019
发布了支持Bootstrap 4的Bootbox 5.0。
原帖
代码取自上面Ammon的回答。更新bootstrap 3.0
function doModal(placementId, heading, formContent, strSubmitFunc, btnText)
{
html = '<div id="modalWindow" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="confirm-modal" aria-hidden="true">';
html += '<div class="modal-dialog">';
html += '<div class="modal-content">';
html += '<div class="modal-header">';
html += '<a class="close" data-dismiss="modal">×</a>';
html += '<h4>'+heading+'</h4>'
html += '</div>';
html += '<div class="modal-body">';
html += formContent;
html += '</div>';
html += '<div class="modal-footer">';
if (btnText!='') {
html += '<span class="btn btn-success"';
html += ' onClick="'+strSubmitFunc+'">'+btnText;
html += '</span>';
}
html += '<span class="btn" data-dismiss="modal">';
html += <?php echo "'".__t("Close")."'"; ?>;
html += '</span>'; // close button
html += '</div>'; // footer
html += '</div>'; // content
html += '</div>'; // dialog
html += '</div>'; // modalWindow
$("#"+placementId).html(html);
$("#modalWindow").modal();
$("#dynamicModal").modal('show');
}
这是我最终用于满足我的需求。还包括一个事件处理程序,用于在关闭时从DOM中删除模态。我只需要一个信息模式,所以我拿出了提交函数和按钮文本参数。
function doModal(heading, formContent) {
html = '<div id="dynamicModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="confirm-modal" aria-hidden="true">';
html += '<div class="modal-dialog">';
html += '<div class="modal-content">';
html += '<div class="modal-header">';
html += '<a class="close" data-dismiss="modal">×</a>';
html += '<h4>'+heading+'</h4>'
html += '</div>';
html += '<div class="modal-body">';
html += formContent;
html += '</div>';
html += '<div class="modal-footer">';
html += '<span class="btn btn-primary" data-dismiss="modal">Close</span>';
html += '</div>'; // content
html += '</div>'; // dialog
html += '</div>'; // footer
html += '</div>'; // modalWindow
$('body').append(html);
$("#dynamicModal").modal();
$("#dynamicModal").modal('show');
$('#dynamicModal').on('hidden.bs.modal', function (e) {
$(this).remove();
});
}
答案 2 :(得分:5)
使用DOM,我创建了Button以及单击Button时弹出的Bootstrap模式。
还在HTML页面的head部分中包含这些内容:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src= "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script
src= "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
这些代码的全部内容都需要用JS文件编写。
//首先,创建一个按钮,在单击时显示Bootstrap Modal
var button = document.createElement("input");
button.className = 'btn btn-info btn-lg';
button.setAttribute("type", "button");
button.setAttribute("data-toggle", "modal");
button.setAttribute("data-target", "#myModal");
button.setAttribute("value", "More Information...");
document.getElementsByTagName('body')[0].appendChild(button);
//创建模式:
var div1 = document.createElement('div');
div1.id = 'myModal';
div1.className = 'modal fade';
div1.setAttribute("role", "dialog");
var innerDiv1m = document.createElement('div');
innerDiv1m.className = 'modal-dialog modal-sm';
div1.appendChild(innerDiv1m);
var innerDiv2m = document.createElement('div');
innerDiv2m.className = 'modal-content';
innerDiv1m.appendChild(innerDiv2m);
var innerDiv3 = document.createElement('div');
innerDiv3.className = 'modal-header';
innerDiv2m.appendChild(innerDiv3);
var buttonM = document.createElement("button");
buttonM.className = 'close';
buttonM.setAttribute("data-dismiss", "modal");
buttonM.setAttribute("aria-hidden", "true");
buttonM.setAttribute("value", "Close");
innerDiv3.appendChild(buttonM);
var headerM = document.createElement("H4");
headerM.className = 'modal-title';
innerDiv3.appendChild(headerM);
var innerDiv31 = document.createElement('div');
innerDiv31.className = 'modal-body';
innerDiv2m.appendChild(innerDiv31);
var para = document.createElement('p');
innerDiv31.appendChild(para);
para.innerHTML = "paragraph";
var innerDiv32 = document.createElement('div');
innerDiv32.className = 'modal-footer';
innerDiv2m.appendChild(innerDiv32);
var closeButton = document.createElement("input");
closeButton.className = 'btn btn-default';
closeButton.setAttribute("data-dismiss", "modal");
closeButton.setAttribute("type", "button");
closeButton.setAttribute("value", "Close");
innerDiv32.appendChild(closeButton);
document.getElementsByTagName('body')[0].appendChild(div1);
//因此,在点击创建的按钮时,模板会在屏幕上弹出。
答案 3 :(得分:4)
与接受的答案非常相似的主题,但写为jQuery插件。我正在寻找一些逻辑来构建一个我正在努力的工具包但却无法找到任何这样写的。
下面有很多代码,但它设计为一次写入然后很容易调用,所以作为一个扰流板,一旦你拥有它所有设置它就像使用一样容易:< / p>
$.fn.alert("utils.js makes this so easy!");
作为一个完整的工作示例:
https://jsfiddle.net/63zvqeff/
页面上不需要任何现有的<div />
,它可以与嵌套对话框一起使用,它是从我正在处理的工具包中获取的,所以我已经包含了所有相关的位它是一个工作的复制/粘贴示例。
(function ($)
{
$.utils = {
// http://stackoverflow.com/a/8809472
createUUID: function ()
{
var d = new Date().getTime();
if (window.performance && typeof window.performance.now === "function")
{
d += performance.now(); //use high-precision timer if available
}
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c)
{
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
}
$.fn.dialogue = function (options)
{
var defaults = {
title: "", content: $("<p />"),
closeIcon: false, id: $.utils.createUUID(), open: function () { }, buttons: []
};
var settings = $.extend(true, {}, defaults, options);
// create the DOM structure
var $modal = $("<div />").attr("id", settings.id).attr("role", "dialog").addClass("modal fade")
.append($("<div />").addClass("modal-dialog")
.append($("<div />").addClass("modal-content")
.append($("<div />").addClass("modal-header")
.append($("<h4 />").addClass("modal-title").text(settings.title)))
.append($("<div />").addClass("modal-body")
.append(settings.content))
.append($("<div />").addClass("modal-footer")
)
)
);
$modal.shown = false;
$modal.dismiss = function ()
{
// loop until its shown
// this is only because you can do $.fn.alert("utils.js makes this so easy!").dismiss(); in which case it will try to remove it before its finished rendering
if (!$modal.shown)
{
window.setTimeout(function ()
{
$modal.dismiss();
}, 50);
return;
}
// hide the dialogue
$modal.modal("hide");
// remove the blanking
$modal.prev().remove();
// remove the dialogue
$modal.empty().remove();
$("body").removeClass("modal-open");
}
if (settings.closeIcon)
$modal.find(".modal-header").prepend($("<button />").attr("type", "button").addClass("close").html("×").click(function () { $modal.dismiss() }));
// add the buttons
var $footer = $modal.find(".modal-footer");
for(var i=0; i < settings.buttons.length; i++)
{
(function (btn)
{
$footer.prepend($("<button />").addClass("btn btn-default")
.attr("id", btn.id)
.attr("type", "button")
.text(btn.text)
.click(function ()
{
btn.click($modal)
}))
})(settings.buttons[i]);
}
settings.open($modal);
$modal.on('shown.bs.modal', function (e) {
$modal.shown = true;
});
// show the dialogue
$modal.modal("show");
return $modal;
};
})(jQuery);
然后,当你想要一个基本的警报()
时,我写了一个辅助函数(function ($)
{
$.fn.alert = function (message)
{
return $.fn.dialogue({
title: "Alert",
content: $("<p />").text(message),
closeIcon: true,
buttons: [
{ text: "Close", id: $.utils.createUUID(), click: function ($modal) { $modal.dismiss(); } }
]
});
};
})(jQuery);
否则,您需要将内容构建为jQuery对象,然后以对象的形式传递,如:
{
title: "", // what ever you want in the title bar
content: $("<p />"), // any DOM structure you can build as a jQuery object
closeIcon: false, // does the dialogue have a X in the tilte bar to close it
id: $.utils.createUUID(), // a reference id
open: function () { }, // a function called after the DOM structure is built but BEFORE rendering
buttons: [ // an array of buttons to include in the footer
// example "close" button, all buttons get a reference to $modal passed into them
// .dismiss() is a function attached to $modal to revert the DOM changes
{ text: "Close", click: function ($modal) { $modal.dismiss(); } }
]
};
答案 4 :(得分:0)
我遇到了同样的问题,经过大量的研究,我终于建立了一个js函数来根据我的要求动态创建模态。使用此功能,您可以在一行中创建弹出窗口,例如:
puyModal({title:'Test Title',heading:'Heading',message:'This is sample message.'})
或者您可以使用其他复杂功能,例如iframe,视频弹出窗口等。
在https://github.com/aybhalala/puymodals上找到它。有关演示,请转到http://pateladitya.com/puymodals/