The simplest way is to save the original value using data()
when the element gets focus. Here is a really basic example:
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 time is negligible.
Here is the same example using delegated events connected to 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/
Delegated events work by listening for an event (focusin
, change
etc) on an ancestor element (document
* in this case), then applying the jQuery filter (input
) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.
*Note: A a general rule, use document
as the default for delegated events and not body
. body
has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document
always exists so you can attach to it outside of a DOM ready handler :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…