Let's say I have to remember the initial height of certain element.
A common practice I see is to save this value with $.data
on that element.
I fail to understand the benefits of this. Why not simply keep a simple variable with that value, or an array with values if there are multiple elements? Keeps the code easy to understand.
The main reason for using data()
is to store data specific to a certain element so it can be accessed later, here's an example
$('.elements').on('click', function() {
$(this).data('value', this.value);
});
$('.elements').on('keyup', function() {
$(this).val( $(this).data('value') );
});
Note that the event handler could match a number of different elements, and using data()
keeps the data associated to each element without using several variables for each element or a complex array.
EXAMPLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With