Javascript 输入 jQuery 在 onchange 之前获取旧值并在更改后获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29118178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input jQuery get old value before onchange and get value after on change
提问by Pekka
I have an input textin jQuery I want to know if it possible to get the value of that input text(type=numberand type=text) before the onchangehappens and also get the value of the same input input text after the onchange happens. This is using jQuery.
我input text在 jQuery 中有一个我想知道是否有可能在发生之前获得input text( type=numberand type=text)onchange的值,并在 onchange 发生后获得相同输入文本的值。这是使用jQuery。
What I tried:
我试过的:
I tried saving the value on variable then call that value inside onchange but I am getting a blank value.
我尝试将值保存在变量上,然后在 onchange 中调用该值,但我得到了一个空白值。
回答by Gone Coding
The simplest way is to save the original value using data()when the element gets focus. Here is a really basic example:
最简单的方法是data()在元素获得焦点时使用保存原始值。这是一个非常基本的例子:
JSFiddle:http://jsfiddle.net/TrueBlueAussie/e4ovx435/
JSFiddle:http : //jsfiddle.net/TrueBlueAussie/e4ovx435/
$('input').on('focusin', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
});
$('input').on('change', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
Better to use Delegated Event Handlers
最好使用委托事件处理程序
Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event timeis negligible.
注意:当可以有多个匹配元素时,使用委托事件处理程序通常更有效。这种方式只添加了一个处理程序(更小的开销和更快的初始化)并且事件时间的任何速度差异都可以忽略不计。
Here is the same example using delegated events connected to document:
以下是使用连接到 的委托事件的相同示例document:
$(document).on('focusin', 'input', function(){
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
console.log("Prev value " + prev);
console.log("New value " + current);
});
JsFiddle:http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/
JsFiddle:http : //jsfiddle.net/TrueBlueAussie/e4ovx435/65/
Delegated events work by listening for an event (focusin, changeetc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chainthen applying the function to only those matching elements that caused the event.
委托的事件通过侦听的事件(工作focusin,change一个祖先元素(上等等)document*在这种情况下),然后将所述的jQuery滤波器(input)仅向元件在气泡链然后将所述函数,只有那些匹配元素导致该事件。
*Note: A a general rule, use documentas the default for delegated events and not body. bodyhas a bug, to do with styling, that can cause it to not get bubbled mouse events. Also documentalways exists so you can attach to it outside of a DOM ready handler:)
*注意:一般规则,使用document作为委托事件的默认值而不是body. body有一个与样式有关的错误,这可能会导致它不会出现冒泡的鼠标事件。也document始终存在,因此您可以在DOM 就绪处理程序之外附加到它:)
回答by mashi
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change). Initial value can be taken from defaultValue property:
当然,您需要手动存储旧值,具体取决于您感兴趣的时刻(在聚焦之前,从上次更改开始)。初始值可以从 defaultValue 属性中获取:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
如 Gone Coding 的回答所示,可以采用聚焦前的值。但你必须记住,价值可以在不专注的情况下改变。
回答by Ehsan
my solution is here
我的解决方案在这里
function getVal() {
var $numInput = $('input');
var $inputArr = [];
for(let i=0; i < $numInput.length ; i++ )
$inputArr[$numInput[i].name] = $numInput[i].value;
return $inputArr;
}
var $inNum = getVal();
$('input').on('change', function() {
// inNum is last Val
$inNum = getVal();
// in here we update value of input
let $val = this.value;
});
回答by thapachaki
I have found a solution that works even with "Select2" plugin:
我找到了一个即使使用“Select2”插件也能工作的解决方案:
function functionName() {
$('html').on('change', 'select.some-class', function() {
var newValue = $(this).val();
var oldValue = $(this).attr('data-val');
if ( $.isNumeric(oldValue) ) { // or another condition
// do something
}
$(this).attr('data-val', newValue);
});
$('select.some-class').trigger('change');
}
回答by Bhojendra Rauniyar
I found this question today, but I'm not sure why was this made so complicated rather than implementing it simply like:
我今天发现了这个问题,但我不确定为什么这会变得如此复杂,而不是简单地实现它:
var input = $('#target');
var inputVal = input.val();
input.on('change', function() {
console.log('Current Value: ', $(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
If you want to target multiple inputs then, use each function:
如果您想针对多个输入,请使用每个函数:
$('input').each(function() {
var inputVal = $(this).val();
$(this).on('change', function() {
console.log('Current Value: ',$(this).val());
console.log('Old Value: ', inputVal);
inputVal = $(this).val();
});
回答by John Andrew Sanchirico
The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.
upvoted 解决方案适用于某些情况,但不是理想的解决方案。Bhojendra Rauniyar 提供的解决方案仅适用于某些场景。var inputVal 将始终保持不变,因此多次更改输入会破坏函数。
The function may also break when using focus, because of the ▲▼ (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:
由于 html 数字输入上的 ▲▼(向上/向下)微调器,使用焦点时该功能也可能会中断。这就是 JT Taylor 拥有最佳解决方案的原因。通过添加数据属性,您可以避免这些问题:
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
回答by Brayan Steven Martínez Vanegas
If you only need a current value and above options don't work, you can use it this way.
如果您只需要一个当前值并且以上选项不起作用,您可以这样使用它。
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
回答by J.T. Taylor
Just put the initial value into a data attribute when you create the textbox, eg
创建文本框时,只需将初始值放入数据属性中,例如
HTML
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
查询
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});

