简体   繁体   English

防止退格在ASP.NET中使用JavaScript转到上一页

[英]Prevent backspace from going to previous page with JavaScript in ASP.NET

I am trying to prevent the backspace key from going to the previous page. 我试图阻止退格键转到上一页。 I have Javascript code to prevent that, and it works... Unless the focus is inside of the textbox element. 我有Javascript代码来防止它,它的工作原理...除非焦点在文本框元素内。 The problem is that the particular textbox is Read-Only. 问题是特定文本框是只读的。 If I remove the Read-Only attribute, then all is well, I can press backspace all I want with the focus in the textbox and it will not go to the previous page, but I need the attribute set. 如果我删除了Read-Only属性,那么一切都很好,我可以在文本框中按下所有我想要的退格键,它不会转到上一页,但我需要属性集。

Below is the code preventing the backspace key from going to the previous page, but allowing it to be used inside of Non Read-Only input fields. 下面是阻止退格键进入上一页的代码,但允许它在非只读输入字段中使用。

        $(document).keydown(function (e) {
            if (e.keyCode == 8 && e.target.tagName != 'INPUT' && e.target.tagName != 'TEXTAREA') {
                e.preventDefault();
            }
        });

The expected outcome is to be able to focus the Read-Only textbox, and press the backspace key and the application NOT go back to the previous page. 预期的结果是能够关注只读文本框,并按退格键和应用程序不返回上一页。

Just check if the field is readonly: 只需检查该字段是否只读:

$(document).keydown(function (e) {
    if (
       e.keyCode == 8 &&
       (e.target.tagName != 'INPUT' || e.target.readOnly) && 
       e.target.tagName != 'TEXTAREA') {
                e.preventDefault();
    }
});

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

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