您可以使用全局变量var saved=false
来检查您的表单是否已保存。要了解表格的变化:
$('form :input').change(function(){saved=false;});
请参阅:jquery 获取所有表单元素:输入、文本区域和选择
当用户离开页面时,您可以触发 beforeunload:
$(window).on('beforeunload', function() {
if(!saved) return 'Leave page?';
});
也可以看看:
要捕捉选项卡更改,您可以使用默认确认(http://www.w3schools.com/js/js_popup.asp):
$('#myTab a').click(function (e)
{
e.preventDefault();
if(!saved)
{
if(confirm('Leave tab?'))
{
$(this).tab('show');
}
}
else
{
$(this).tab('show');
}
});
或者您可以尝试构建自己的确认对话框:
请注意,您似乎无法在卸载之前捕获窗口,但要更改选项卡:
html:
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">...</div>
<div class="tab-pane" id="profile"><form><input type="text"><input type="submit" class="btn btn-success"></form></div>
<div class="tab-pane" id="messages">...</div>
<div class="tab-pane" id="settings">...</div>
</div>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>Form not saved!</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id="leavetab" class="btn btn-primary">Leave tab</button>
</div>
</div>
javascript:
var已保存=真;var 确认 = 假;
var thistab = null;
函数 checksave() { 返回已保存;}
$(function () { $('#myTab a:last').tab('show');
$('#myTab a').click(function (e)
{
e.preventDefault();
thistab = $(this);
if(!checksave()){ $('#myModal').modal(); return false;}
thistab = null;
if(saved || confirmed)
{
$(this).tab('show');
saved = false;
confirmed = false;
}
});
//see: https://stackoverflow.com/questions/12862601/jquery-get-all-form-elements-input-textarea-select
$('form :input').change(function(){saved=false; confirmed = false;});
$('#myModal').on('hidden', function () {
return false;
});
// modal click set confirmed to true
$('#leavetab').click(function()
{
{
$('#myModal').modal('hide');
thistab.tab('show');
saved = false;
confirmed = false;
}
});
});