按键后jQuery获取输入值 [英] jQuery get input value after keypress
问题描述
我有以下功能:
$(document).ready(function() {
$("#dSuggest").keypress(function() {
var dInput = $('input:text[name=dSuggest]').val();
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
出于某种原因,对于第一个按键,我得到一个空字符串到控制台日志。
For some reason, for the first keypress, I'm getting an empty string to the console log.
推荐答案
这是因为 keypress
事件在之前被解雇 / em>新元素被添加到元素的值
中(因此第一个 keypress
事件在添加第一个字符,而值
仍为空。您应该使用 keyup
代替,在添加字符后触发。
This is because keypress
events are fired before the new character is added to the value
of the element (so the first keypress
event is fired before the first character is added, while the value
is still empty). You should use keyup
instead, which is fired after the character has been added.
请注意,如果您的元素 #dSuggest
与输入相同:text [name = dSuggest]
,您可以简化这个代码相当大(如果不是这样,有一个名称与另一个元素的 id
相同的元素不是一个好主意)。
Note that, if your element #dSuggest
is the same as input:text[name=dSuggest]
you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id
of another element is not a good idea).
$('#dSuggest').keypress(function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
这篇关于按键后jQuery获取输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!