使用jQuery选择DropDownlist时如何防止AutoPostBack

Col*_*lin 2 asp.net jquery javascript-events

我想在用户选择DropDownList中的项目时显示确认对话框.如果用户按"取消",我想停止回发.这是我添加到onchange事件的函数:

function imitateConfirmUnload(event) {
    if (window.onbeforeunload = null)
        return true;

    return confirm("Are you sure you want to navigate away from this page?\n\nYou have unsaved changes\n\nPress OK to continue or Cancel to stay on the current page.");
}
Run Code Online (Sandbox Code Playgroud)

这是我的启动脚本中的相关代码,用于将处理程序添加到事件中:

function addConfirmToWarnClasses() {

    $('.warn').change(function() {
        imitateConfirmUnload()
    });
}
Run Code Online (Sandbox Code Playgroud)

问题是即使用户选择"取消",也会发生回发.如果我将处理程序移动到click事件,它就可以工作.但它对我来说很笨拙.

编辑

更正:它不起作用,因为对话框阻止选择,因此当用户选择"确定"时,没有发生任何更改,并且在您需要时不会回发!

编辑2

DropDownList位于UpdatePanel内部,因此可能会影响行为.

Hom*_*mer 5

阅读完这个解决方案后,我刚刚删除了AutoPostBack我的DropDownLists并使用了它,因为它非常简单:

$("#DropDownList1").change(function (e) {
    if ($(this).val() == "0") {
        //do nothing
    }
    else {
        //do postback
        setTimeout("__doPostBack('DropDownList1','')", 0);
    }
});
Run Code Online (Sandbox Code Playgroud)

或者如果你DropDownLists想要制作多个AutoPostBack:

$("select").change(function (e) {
    if ($(this).val() == "0") {
        //do nothing
    }
    else {
        //do postback
        setTimeout("__doPostBack('" + this.id + "','')", 0);
    }
});
Run Code Online (Sandbox Code Playgroud)