我在ASP.NET MVC中使用模态窗口遇到了奇怪的问题。我创建了一个链接来显示模态窗口。模态窗口弹出并包含一个按钮 - 保存按钮。我附加了一个点击事件处理程序到该按钮上,以便保存窗口的内容,然后关闭它。整个机制看起来像这样:
// this link shows up a modal window
@Html.ActionLink("Add", "Add", "Index", null, new { id = "actionLinkAdd" });
and javaScript
$(function () {
debugger;
$("#actionLinkAdd").on("click", function (event, action) { // attaching to click event
debugger;
event.preventDefault(); //disabling default handler
var $dialog = $('<div></div>');
var $url = $(this).attr('href');
$dialog.empty();
var $kendoWindow = $dialog.kendoWindow({ //window creating
height: "200px",
title: "Dodaj",
visible: false,
width: "200px",
actions: ["Close"],
content: $url // loading of the window's content (partialView)
}).data("kendoWindow");
$kendoWindow.center();
$kendoWindow.open();
function onButtonSaveClick(event) {
debugger;
event.preventDefault();
var $url = $('#target').attr("action");
$.ajax({
url: $url,
type: "POST",
data: $('#target').serialize(),
success: function (response) {
$("#btnSave").unbind("click");
$kendoWindow.close();
$kendoWindow.destroy();
},
error: function (args) {
debugger;
$("#btnSave").unbind("click");
$kendoWindow.content(args.responseText);
}
});
}
$('#btnSave').live("click", onButtonSaveClick); // attaching to click event on save button in the modal window
});
});
一切几乎都很顺利,问题在于onButtonClick()函数会被触发多次。例如,如果我打开模态窗口两次,这个函数也会被调用两次。对我来说这很奇怪,因为我关闭了模态窗口,销毁了它,并且解除了所有绑定到btnSave的点击事件(我还尝试使用on和off函数,但窗口的行为仍然相同)。这种行为的原因是什么?