[英]What's the reason for storing data with .data() instead of using plain variables?
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. 我看到的常见做法是在该元素上使用$.data
保存此值。
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 使用data()
主要原因是存储特定于某个元素的数据,以便以后可以访问,这是一个例子
$('.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. 请注意,事件处理程序可以匹配许多不同的元素,并且使用data()
可以保留与每个元素关联的数据,而无需为每个元素或复杂数组使用多个变量。
It allows the function to be reused to apply the same effect to other elements (without having to deal with closures). 它允许重用该函数以将相同的效果应用于其他元素(无需处理闭包)。
It allows the value to be initialized with HTML. 它允许使用HTML初始化值。
It makes it easier for developer tools to inspect the data. 它使开发人员工具更容易检查数据。
Basically because le you save information INSIDE A NODE, preventing possible variable name conflicts and without the need to pass variables around. 基本上是因为你在INSIDE A NODE中保存信息,防止可能的变量名冲突而不需要传递变量。 All the needed informations about a node, stay with the node itself 有关节点的所有必需信息都与节点本身保持一致
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.