gpt4 book ai didi

javascript - 离开未保存表单的页面时发出警报( typescript )

转载 作者:行者123 更新时间:2023-12-03 01:37:02 26 4
gpt4 key购买 nike

我有 ts 脚本,其中包含处理“未保存” 文本输入的代码

这是脚本代码

export class Unsave {
public static unsave_check(): void {
let unsaved = false;
$(":input").change(function(){
unsaved = true;
console.log(unsaved);
});

function unloadPage(){
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}

}
}

然后我在其他脚本中使用它,如下所示

`window.onbeforeunload = Unsave.unsave_check();`

但正如我所见,function unloadPage() 从未被命中,为什么会这样?我看到 unsaved 正在将值更改为 true。但是当我回去时,我没有收到任何警报消息。

如何解决这个问题?

感谢帮助

最佳答案

我认为你应该在表单初始化时调用Unsave.unsave_check(),并将unloadPage绑定(bind)到window.onbeforeunload(并且您可以将其设为静态 - 或使用其他方法将其设为非静态并实例化该对象)。您还应该将值 unsaved 从函数作用域移至私有(private)类字段,以便两种方法都可以访问它

export class Unsave {
private unsaved: boolean = false;

public register() {
$(":input").change(() => {
this.unsaved = true;
console.log(this.unsaved);
});
}

public unloadPage() {
if (this.unsaved) {
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
}

// call this after form init
const unsaveChecker = new Unsave();
unsaveChecker.register()
window.onbeforeunload = () => unsaveChecker.unloadPage()

关于javascript - 离开未保存表单的页面时发出警报( typescript ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com