joh*_*hna 5 javascript asp.net jquery
我只想在用户关闭我的 ASP.NET Web 窗体页面或离开它时向用户显示一条消息。如果他们单击任何 Button、LinkButton、AutoPostBack 元素或任何其他将回发的元素,那么我不想显示该消息。
到目前为止,我有以下代码:
<script type="text/javascript">
var postback = false;
addToPostBack = function(func) {
var old__doPostBack = __doPostBack;
if (typeof __doPostBack != "function") {
__doPostBack = func;
} else {
__doPostBack = function(t, a) {
if (func(t, a)) old__doPostBack(t, a);
}
}
};
$(document).ready(function() {
addToPostBack(function(t,a) {
postback = true;
});
});
$(window).bind("beforeunload", function() {
if (!postback) {
return "message";
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
这部分有效,但似乎阻止了 AutoPostBack 事件的触发,并且仍然显示 LinkButtons 等的消息。
我怎样才能做到这一点?
这将获取调用 __doPostBack 时的时间戳,然后执行默认行为。
仅当 onbeforeunload 事件的时间戳与最新 __doPostBack 时间戳之间的差异大于 allowedWaitTime 时,才会显示您的自定义消息。
用法:将其包含在页面的任何位置。
现在这也将处理 WebForm_DoPostBackWithOptions
(function ($) {
if (typeof $ !== 'function') {
throw new Error('jQuery required');
}
/* The time in milliseconds to allow between a __doPostBack call and
showing the onbeforeunload message. */
var allowedWaitTime = 100,
timeStamp = new Date().getTime(),
// Each function to override
baseFuncs = {
__doPostBack: this.__doPostBack,
WebForm_DoPostBackWithOptions: this.WebForm_DoPostBackWithOptions
};
// Set timeStamp when each baseFunc is called
for (var baseFunc in baseFuncs) {
(function (func) {
this[func] = function () {
var baseFunc = baseFuncs[func];
timeStamp = new Date().getTime();
if (typeof baseFunc === 'function') {
baseFunc.apply(arguments.callee, arguments);
}
}
})(baseFunc);
}
/* Form submit buttons don't call __doPostBack so we'll set timeStamp
manually on click. */
$('input[type="submit"]').click(function () {
timeStamp = new Date().getTime();
});
$(this).on('beforeunload', function (e) {
// Only return string if allowedWaitTime has elapsed
if (e.timeStamp - timeStamp > allowedWaitTime) {
return 'message';
}
});
}).call(window, jQuery);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2362 次 |
| 最近记录: |