繁体   English   中英

离开页面时提示用户

[英]prompting a user when leaving page

在我的页面上,我有一个名为cbOrderSpareCustomer的组合框。 默认情况下,所选索引设置为0。

当用户更改它时,我认为该页面包含数据,并且当用户决定离开该页面时,我想提醒他让他知道数据将丢失。

我已经看过很多关于此的文章,但是我对javascript还是很陌生,所以我可以使用一些帮助。

我了解我必须使用:

<script>
window.onbeforeunload= function() { return "Custom message here"; };
</script>

但是,如何使它与组合框一起使用?

if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.

我也想阻止它在每次回发中显示提示。

我想看一个例子。

您会在客户端的下拉列表中查看索引,您的代码可能如下所示:

<script>
window.onbeforeunload= function() 
    { 
        if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0)
        {
            return "Custom message here"; 
        }
        else
        {
            return true;
        }
    };
</script>

我认为...

window.onbeforeunload = function(e) {
    if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) {
        if (!confirm('Are you sure')) {
            return false;
        }
    }
}

请按照以下步骤进行操作

  1. 使用以下代码将onchange属性添加到服务端的组合框中: <select id="cbOrderSpareCustomer" onchange="setDirty()">
  2. 如下定义您的JavaScript

    var isDirty = true;
    function setDirty() { isDirty = true; } window.onbeforeunload = function () { if (isDirty) { return confirm('Your unsaved changes will be lost'); } }

如果您使用的是JQuery

<script type="text/javascript">
    $(window).bind('beforeunload', function () {
        if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) {
            return 'Your data will be lost.';
        }
    });
</script>

您不希望其他返回true,否则它仍会提示(至少IE提示)

我的解决方案:

<script type="text/javascript"
function setDirty() {
            window.onbeforeunload = function () {
                return 'The data will be lost if you leave this page!'
            }
        }
</script>

将属性onCange =“ setDirty()”添加到下拉列表中。

谢谢大家的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM