如何使用 jQuery 和 JavaScript 防止文本字段失去焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7626319/
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
How to prevent an textfield losing focus using jQuery and JavaScript?
提问by Jonas
I have a textfield <input type="text"/>
that I want to validate when the focus is lost. If the input is not valid, I want to prevent the focus moving to the next element, or in other words keep the focus at the invalid input until it's valid.
我有一个文本字段<input type="text"/>
,我想在失去焦点时进行验证。如果输入无效,我想阻止焦点移动到下一个元素,或者换句话说,将焦点保持在无效输入上,直到它有效为止。
How can I do that using jQuery and JavaScript?
我如何使用 jQuery 和 JavaScript 做到这一点?
I have tried with this code, but it doesn't work (jsFiddle):
我已尝试使用此代码,但它不起作用(jsFiddle):
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script>
$(function() {
$('.hello').bind('focusout', function(e) {
if(!isValid($(this).val())) {
e.preventDefault();
$(this).foucus();
}
});
});
function isValid(str) {
if(str === "hello") {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
Only valid content: <b>hello</b><br>
<input type="text" class="hello"/>
<button>Dummy</button>
</body>
</html>
回答by FishBasketGordo
It's just a typo. Change:
这只是一个错字。改变:
$(this).foucus();
To:
到:
$(this).focus();
Also, you might want to make it easier for your users to correct their mistake by also calling select
on the textbox. That way, they can just begin typing again to change the value:
此外,您可能还希望通过调用select
文本框来让您的用户更容易纠正他们的错误。这样,他们就可以再次开始输入以更改值:
$(this).focus().select();
Here is a working example.
这是一个工作示例。
Note: This answer fixes the problem at hand, i.e. the question that was asked. On a broader scale, I do agree with the others who are saying that one shouldn't lock the user into a field. A better way of doing this would be to validate the whole form on submit, letting the users see all the problems and fixing them all at once, instead of bugging them throughout.
注意:这个答案解决了手头的问题,即被问到的问题。在更广泛的范围内,我确实同意其他人所说的不应该将用户锁定在一个领域。一个更好的方法是在提交时验证整个表单,让用户看到所有的问题并立即修复它们,而不是从头到尾地调试它们。
回答by Doozer Blake
The event should be blur
you're looking for. And your original jsfiddle had a typo (.foucus instead of focus)
该事件应该是blur
您正在寻找的。你原来的 jsfiddle 有一个错字(.foucus 而不是 focus)
And as a commenter said, visitors won't like this behavior.
正如一位评论者所说,访客不会喜欢这种行为。
回答by Otto Kanellis
$("#input").focus();
$("#input").blur(function() {
setTimeout(function() { $("#input").focus(); }, 0);
});
回答by realshadow
Instead of $(this).focus()
, use $(this).trigger('focus');
. And the event should be blur
, not focusout
.
而不是$(this).focus()
,使用$(this).trigger('focus');
。而事件应该是blur
,不是focusout
。
Edit: oh well, focus()
will work as well :)
编辑:哦,好吧,focus()
也会起作用:)