Javascript 使用类检查文本框中的值是否已更改
我有带.numeric类的文本框。我希望在编辑该值后检查该值是否已更改 我在谷歌之后发现了这段代码Javascript 使用类检查文本框中的值是否已更改,javascript,jquery,Javascript,Jquery,我有带.numeric类的文本框。我希望在编辑该值后检查该值是否已更改 我在谷歌之后发现了这段代码 var previousValue = $("#elm").val(); $("#elm").keyup(function(e) { var currentValue = $(this).val(); if(currentValue != previousValue) { previousValue = currentValue; alert("
var previousValue = $("#elm").val();
$("#elm").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
但此代码仅适用于一个文本字段(id为
#elm
)。如果我想让它适用于多个字段(共享类numeric
),该怎么办?只需更改选择器以匹配它就可以了
$(".numeric").on('keyup', function(e) {
if (e.isTrigger) $(this).data('val', this.value);
if(this.value != $(this).data('val')) {
$(this).data('val', this.value);
alert("Value changed!");
}
}).trigger('keyup');
与其只是从谷歌复制粘贴代码,不如花几个小时来学习它的工作原理。为此,请使用:
$(".numeric").each(function(){
$(this).data("value", $(this).val());
});
$(".numeric").keyup(function(e) {
var currentValue = $(this).val();
var preVal = $(this).data("value");
alert(preVal);
if(currentValue != preVal) {
$(this).data("value", currentValue);
preVal = currentValue;
alert("Value changed!");
}
});
尝试在一个字段中键入55
,在另一个字段中键入66
,在另一个字段中键入77
,注意每个字段的前一个值仍然不同非常简单:
var currentValue ;
$(".numeric").keydown(function(e) {
currentValue = $(this).val();
});
$(".numeric").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
alert("Value changed!");
}
});
以下是使用“更改”触发器将涵盖用户通过鼠标操作在字段中复制粘贴值的情况
$(".numeric").each(function(){
$(this).data("value", $(this).val());
});
$(".numeric").on('change', function(e) {
var currentValue = $(this).val();
var preVal = $(this).data("value");
if(currentValue != preVal) {
preVal = currentValue;
alert("Value changed!");
}
});
对不起。最后我找到了最好的解决办法。我很容易。我们可以在jquery中使用change函数。更改值后,它将启动功能。我想要的
$('.numeric').change(function () {
alert('Changed');
});
现在,您可以更改绑定事件。您可以将事件绑定到模糊或调出焦点。这个问题似乎离题了,因为它非常明显!我找到了答案。感谢所有回复。如果返回多个输入,则切换选择器将无法正常工作。。。他们仍然会共享一个previousValue变量。@SamR-我想我必须发布一个真实的答案
$(".numeric").each(function(){
$(this).attr('data-pre_value', $(this).val());
});
$(".numeric").bind('keyup', function(){
var pre_value = $(this).attr('data-pre_value');
var current_value = $(this).val();
if(pre_value != current_value){
alert('value has changed');
}
});