gpt4 book ai didi

javascript - 将 Form 的旧值与新值进行比较

转载 作者:行者123 更新时间:2023-11-28 10:16:39 25 4
gpt4 key购买 nike

我有一个包含多个字段的表单,其中一个是“计数器”,它不断变化。编辑表单时,我需要跟踪某些字段是否发生更改,并将“计数器”字段设置为提交时修改的字段数。例如,如果计数器的旧值为 10,并且修改了 field1、field2 和 field3,则表单提交计数器应增加到 13。

下面是我尝试为一个字段执行的操作,但它无法正常工作。我不仅需要检查一个字段,还需要检查其他一些字段。任何帮助表示赞赏。谢谢!

$(document).ready(function(){
var oldVal = getOldValue("field1");
var oldCounter = parseInt(getOldValue("Counter"));
var curCounter;

$('field1').change(function(){
var newVal= $(this).val();

if(oldVal.val() == newVal.val()){
curCounter = oldCounter +1;
setField("Counter", parseInt(curCounter));
}

});

});

最佳答案

您的 if 语句不正确。当值发生更改 (.change()) 时触发,但您通过 if(oldVal.val() == newVal.val()) 检查值是否相同

此外,.val() 是 jQuery 对象的方法,因此除非函数 getOldValue() 返回 jQuery 对象,否则您的 if 语句可能不会执行您期望的操作。

我要做的是将表单字段的 oldValues 存储在表单字段的 data 属性中,以便您可以从 .change() 中轻松访问它> 事件,例如:

$(document).ready(function(){

var oldCounter = parseInt(getOldValue("Counter"), 10); // use the second argument '10' here or you might get strange results
var curCounter = oldCounter;


$('.field').each(function() {
// store the old value
$(this).data("oldValue", getOldValue($(this).attr("id")));
})
.change(function(){
// compare values, increase counter if it is different than the original value
if($(this).data("oldValue") != $(this).val()) {
curCounter++;
setField("Counter", curCounter);
}
});

});

未经测试的代码,但您明白了要点,希望这有帮助

关于javascript - 将 Form 的旧值与新值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6479895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com