为什么按后退键时输入的文本没有被删除

why input text not deleted when press back button?

本文关键字:文本 删除 输入 为什么      更新时间:2023-09-26

我做了一个简单的演示,其中我限制弹出屏幕不关闭时后退按钮按下。但我能够做到这一点,但当我写的东西在文本字段我不能删除文本。我们能两样都做吗?意味着限制弹出屏幕以及从文本字段中删除文本?

<!DOCTYPE html>
<html>
<head>
<link href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div data-role="page">
  <div data-role="header">
    <h1>Welcome To My Homepage</h1>
  </div>
  <div data-role="main" class="ui-content">
    <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all">Show Popup</a>
    <div data-role="popup" id="myPopup" data-dismissible='false'>
    <div data-role="fieldcontain">
        <label for="testCaseIDValue">TestCase Name:</label>
        <input type="text" name="testCaseIDValue" id="testCaseInnerIDValue" value="" class="inputTextTestCase"/>
    </div>
    <a href="#" data-role="button" id="doneInnerPopUp" class="common-button">Done</a>
  </div>
  <div data-role="footer">
    <h1>Footer Text</h1>
  </div>
</div> 
</body>
</html> 

js代码
$('body').keydown(function(e) {
    if($('#myPopup').is(':visible')) {
        if(e.keyCode == 8) { // 8 is backspace
            e.preventDefault();
        }
    }
});

您可以尝试创建类型为reset的隐藏input假设它有clearItid

,你可以说:

$('body').keydown(function(e) {
    if($('#myPopup').is(':visible')) {
        if(e.keyCode == 8) { // 8 is backspace
           $('#clearIt').trigger("click");       
 }
    }
});

它会重置输入文本当它在一个表单

您刚刚禁用了整个文档(在您的case body中)的退格,包括输入。
为了不影响输入,可以在

条件中检查它是否是活动元素。
$(document).on('keydown', function(e) {
    if( 
        $('#myPopup').is(':visible') && 
        (!$('#myPopup input').is(':focus')) &&
        e.which === 8
    ) {
        e.preventDefault();
    }
});

小提琴