我的ts脚本带有处理"unsaved"
文本输入的代码
这是脚本的代码
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()
从未被命中,为什么呢?我看到未保存的值正在更改为true。但是当我回去时,没有收到任何警告消息。
如何解决此问题?
感谢帮助
最佳答案
我认为您应该在表单初始化后调用Unsave.unsave_check()
并将unloadPage
绑定到window.onbeforeunload
(您也可以将其设置为静态-或使用其他方法将其静态化并实例化该对象)。
您还应该将值unsaved
从函数作用域中移出,也许移动到私有类字段中,以便两个方法都可以访问它
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()