Javascript jquery-仅捕获文本输入中的新值
我试图创建一个JQuery方法来告诉我用户在文本输入中写了什么。例如,如果有一个带有文本Javascript jquery-仅捕获文本输入中的新值,javascript,jquery,input,Javascript,Jquery,Input,我试图创建一个JQuery方法来告诉我用户在文本输入中写了什么。例如,如果有一个带有文本foo的输入,并且用户在b中键入,我想捕捉它。如果用户随后键入a,我只想捕获a,而不是ba 我该怎么做 编辑:我使用以下代码: $(".writetags").each(function(){ var elem = $(this); elem.bind("keyup", function() { elem.data("oldVal", $(this).d
foo
的输入,并且用户在b
中键入,我想捕捉它。如果用户随后键入a
,我只想捕获a
,而不是ba
我该怎么做
编辑:我使用以下代码:
$(".writetags").each(function(){
var elem = $(this);
elem.bind("keyup", function() {
elem.data("oldVal", $(this).data("newVal") || "");
elem.data("newVal", $(this).val());
var oldVal = elem.data("oldVal");
var newVal = $(this).val();
console.log("Was "+oldVal+" is "+newVal);
var newChar = newVal.charAt(newVal.length-1);
var oldChar = oldVal.charAt(oldVal.length-1);
console.log("The user just typed in "+newChar+" instead of "+oldChar);
});
});
$(".writetags").each(function(){
var elem = $(this);
elem.bind("keyup", function() {
elem.data("oldVal", $(this).data("newVal") || "");
elem.data("newVal", $(this).val());
var oldVal = elem.data("oldVal");
var newVal = $(this).val();
console.log("Was "+oldVal+" is "+newVal);
var newChar = newVal.charAt(newVal.length-1);
var oldChar = oldVal.charAt(oldVal.length-1);
console.log("The user just typed in "+newChar+" instead of "+oldChar);
});
});
这是一个通用代码,用于侦听网页中的所有文本输入更改:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("oldVal", $(this).data("newVal") || "");
$(this).data("newVal", $(this).val());
console.log($(this).data("oldVal"));
console.log($(this).data("newVal"));
});
});
使用
keyCode
事件中的keyCode
并使用String.fromCharCode
获取字符:-
$('input')。按键(函数(事件){
var character=String.fromCharCode(event.which | | | event.charCode | | event.keyCode);
console.log(字符);
})
谢谢大家,但我还是用以下代码做到了:
$(".writetags").each(function(){
var elem = $(this);
elem.bind("keyup", function() {
elem.data("oldVal", $(this).data("newVal") || "");
elem.data("newVal", $(this).val());
var oldVal = elem.data("oldVal");
var newVal = $(this).val();
console.log("Was "+oldVal+" is "+newVal);
var newChar = newVal.charAt(newVal.length-1);
var oldChar = oldVal.charAt(oldVal.length-1);
console.log("The user just typed in "+newChar+" instead of "+oldChar);
});
});
$(".writetags").each(function(){
var elem = $(this);
elem.bind("keyup", function() {
elem.data("oldVal", $(this).data("newVal") || "");
elem.data("newVal", $(this).val());
var oldVal = elem.data("oldVal");
var newVal = $(this).val();
console.log("Was "+oldVal+" is "+newVal);
var newChar = newVal.charAt(newVal.length-1);
var oldChar = oldVal.charAt(oldVal.length-1);
console.log("The user just typed in "+newChar+" instead of "+oldChar);
});
});
只需将一个函数附加到输入元素的keypress事件,并从事件objecttrap获取按下的键event@FrebinFrancis但我如何检测输入中写入的新字符?请将您的解决方案作为您的答案发布question@TobyAllen我已经做了,看看下面