javascript 防止退格在 AngularJS 中导航回来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29006000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent backspace from navigating back in AngularJS
提问by gyss
I faced this issue in my AngularJS webapp.
我在我的 AngularJS webapp 中遇到了这个问题。
When a user enters a page with a form to fill and he starts typing, if he presses the backspace key and the focus is not on the input text, then the page goes to the previous state.
当用户进入带有要填写的表单的页面并开始键入时,如果他按下退格键并且焦点不在输入文本上,那么页面将进入之前的状态。
I looked up this solutionusing jQuery, but it doesn't seem the appropiate way for achieve this in AngularJS.
我使用 jQuery查找了这个解决方案,但它似乎不是在 AngularJS 中实现这一点的合适方法。
回答by Jai
There is $document
in angular js:
有$document
角度的js:
angular.module('yourModule', [])
.controller('yourController', ['$scope', '$document', function($scope, $document) {
$document.on('keydown', function(e){
if(e.which === 8 && ( e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT" ) ){ // you can add others here inside brackets.
e.preventDefault();
}
});
}
]);
Plnkr Demo.
Plnkr 演示。
You can see in the demo i have used only for "INPUT"
nodeName and it does not prevent the default of the backspace key on text input but not on textarea
because we have not handled it in the condition.
您可以在演示中看到我仅用于"INPUT"
nodeName 并且它不会阻止文本输入上的退格键的默认值,但不会阻止,textarea
因为我们没有在条件中处理它。
回答by Anatolii Chmykhalo
I can't comment "accepted answer", but it will work not right, as condition
我不能评论“接受的答案”,但它不会正常工作,因为条件
e.which === 8 && e.target.nodeName !== "INPUT" || e.target.nodeName !== "SELECT"
with logic error, so you can use
有逻辑错误,所以你可以使用
e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"
or answer that wrote @ThisIsMarkSantiago.
或写@ThisIsMarkSantiago 的答案。
回答by Libu Mathew
Add the below script in your controller
在您的控制器中添加以下脚本
var rx = /INPUT|SELECT|TEXTAREA/i;
$document.on("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
Or you can use Jquery
或者你可以使用 Jquery
$(function(){
var regx = /INPUT|SELECT|TEXTAREA/i;
$(document).bind("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!regx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
});
回答by ThisIsMarkSantiago
I got this answer here: How can I disabling backspace key press on all browsers?
我在这里得到了这个答案: 如何在所有浏览器上禁用退格键?
$(document).keydown(function(e) {
var nodeName = e.target.nodeName.toLowerCase();
if (e.which === 8) {
if ((nodeName === 'input' && e.target.type === 'text') ||
nodeName === 'textarea') {
// do nothing
} else {
e.preventDefault();
}
}
});
Just put it inside your controller.
把它放在你的控制器里。