参考this主题,我创建了ajax模式:
MAIN JS FILE
(function ($)
{
$.fn.ajaxmodal = function (options)
{
var defaults = {
title: "",
content: $("<p />"),
id: "ajaxmodal",
open: function () { },
};
var settings = $.extend(true, {}, defaults, options);
if (settings.js){
var js = document.createElement("script");
js.id = "script"+settings.id;
js.type = "text/javascript";
js.innerHTML += settings.js;
}
if (settings.css){
var css = document.createElement("style");
css.id = "style"+settings.id;
css.type = "text/css";
css.innerHTML += settings.css;
}
// create the DOM structure
var $modal = $("<div />").attr("id", settings.id).attr("role", "dialog").addClass("modal fade").attr("data-keyboard", "false").attr("data-backdrop", "static")
.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))
)
);
$modal.shown = false;
this.dismiss = function ()
{
if (!$modal.shown)
{
window.setTimeout(function ()
{
$modal.dismiss();
}, 50);
return;
}
$modal.modal("hide");
$modal.prev().remove();
$modal.empty().remove();
$("body").removeClass("modal-open");
if (settings.js){ $("#script"+settings.id).remove(); }
if (settings.css){ $("#style"+settings.id).remove(); }
}
$modal.find(".modal-header").prepend($("<button />").attr("type", "button").addClass("close").html("×").click(function () { $modal.dismiss() }));
settings.open($modal);
$modal.on('shown.bs.modal', function (e) {
$modal.shown = true;
if (settings.js){ $("body").append(js); }
if (settings.css){ $("body").append(css); }
});
$modal.modal("show");
return $modal;
};
})(jQuery);
我通过jq / php加载内容
MAIN JS FILE:
$(document).on('click', '.open_modal', function() {
var a = 'my..vars...';
$.post("/ajax_modal.php", a, function(o){
if(o.s){
// open modal
$.fn.ajaxmodal(o.o);
} else {
// invalid access
$.notify(o.m);
}
},'json');
});
AJAX.PHP:
$obj = array(
'title' => 'My title',
'content' => '
<div class="box">
<button type="button" class="btn clickme">Button</button>
</div>
<div class="box2">
content
</div>
',
'id' => 'modal-'.$id,
'js' => '
$(document).on("click", ".clickme", function() {
var a = "my..vars..";
$.post("/ajax_modal.php", a, function(o){
if(o.s){
//
// PROBLEM
//
$.fn.ajaxmodal.dismiss;
$.notify(o.m);
} else {
// dismiss modal
$.notify(o.m);
}
},"json");
});
',
'css' => '
.box {display: block; width: 100%;}
'
);
$out = array(
's'=>1,
'o'=>$obj
);
echo json_encode($out);
通过ajax我创建模态并注入内容和CSS&amp; JS进入正文,问题是关闭模态的函数不起作用($ .fn.ajaxmodal.dismiss;或$ .fn.ajaxmodal.dismiss();不起作用)关闭模态并从正文中删除内容和脚本。我试过了
IN MAIN JS
if(o.s){
var ajax_mod = $.fn.ajaxmodal(o.o);
} else {
AND IN ajax.php
if(o.s){
ajax_mod.dismiss();
// OR
// ajax_mod.dismiss;
$.notify(o.m);
} else {
但那也不起作用..我怎样才能做到这一点?