简体   繁体   English

如何检测textarea或输入type =“ text”编辑?

[英]How to detect textarea or input type=“text” editing?

I use this snippet to prevent the user from accidentally navigating away from the editing page: 我使用此代码段来防止用户意外地离开编辑页面:

var warning = false;
window.onbeforeunload = function() {
  if (warning) {
    return '';
  }
}

Now I want to set the variable warning to be true if any of the textarea or input type="text" has been modified, I want to use the onkeyup event such as in: 现在,如果已修改任何textarea或输入type =“ text”,我想将变量警告设置为true,我想使用onkeyup事件,例如:

document.getElementById('textarea_id').onkeyup = function() {
    warning = true;
}

But it's not working. 但这不起作用。 Don't quite want to use jQuery on this. 不想在此上使用jQuery。 Any insights? 有什么见解吗?

Update: 更新:

Changed to this: 改为:

var warning = false;
window.onbeforeunload = function() { 
  if (warning) {
    return 'You have unsaved changes.';
  }
}
document.getElementById('textarea_id').onkeyup = function() {
    warning = true;
}

Yet it's still not working. 但是它仍然无法正常工作。

By the way, it's put in in the of the page. 顺便说一句,它放在页面的中。 There are no javascript anywhere else. 其他任何地方都没有JavaScript。

The return value of the onbeforeunload event is only used if it isn't equivalent to false . onbeforeunload事件的返回值仅在不等于false

Change return ''; 更改return ''; to

return 'You have unsaved changes.';

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

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