基于字符串长度的 JQuery 函数失火
当输入内容包含 3 个或更多字符且不等于占位符时,以下函数应显示一个面板。
$('#search').keydown(function(){
$('#header .suggestion').removeClass('visible');
var slength = $(this).val();
if(slength.length > 2 && slength != $(this).attr('placeholder')){
//activate AJAX script
$('#header .results').addClass('visible');
}
else {
$('#header .results').removeClass('visible');
}
});
相反,直到显示 5 个字符后才会出现。为什么。
奇妙
The following function should reveal a panel when the input has 3 or more characters inside it and is not equal to the placeholder.
$('#search').keydown(function(){
$('#header .suggestion').removeClass('visible');
var slength = $(this).val();
if(slength.length > 2 && slength != $(this).attr('placeholder')){
//activate AJAX script
$('#header .results').addClass('visible');
}
else {
$('#header .results').removeClass('visible');
}
});
Instead it doesn't appear until 5 characters are displayed. Why.
Marvellous
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
keydown
和keypress
事件在浏览器处理输入之前调用。在这些事件期间,开发人员可以添加一种方法来阻止用户输入文本。因此,当您收听
keydown
函数时,$(this).val()
不会返回“预期”值。图像(用户已经将注意力集中在输入字段上):
要获取输入的“预期”值,您必须使用
keyup
事件而不是keydown
。The
keydown
andkeypress
events are called BEFORE the browser has processed the input. During these events, the developer can add a method to prevent the user from entering text.So, when you're listening to the
keydown
function, the$(this).val()
does NOT return the "expected" value.An image (the user has already focused on the input field):
To get the "expected" value of the input, you have to use the
keyup
event instead ofkeydown
.