简体   繁体   English

使用.data()而不是使用纯变量存储数据的原因是什么?

[英]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()可以保留与每个元素关联的数据,而无需为每个元素或复杂数组使用多个变量。

EXAMPLE

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.

相关问题 为什么使用jQuery数据来存储变量而不是普通的JavaScript对象? - Why use jQuery data to store variables instead of plain JavaScript objects? 使用普通JS而不是JQUERY发布表单数据并将响应存储在变量中 - Posting form data and storing the response in a variable using plain JS not JQUERY 在Javascript中使用===而不是==和typeof的原因是什么? - What's the reason to use === instead of == with typeof in Javascript? 将数据存储在 arrays 而不是数据库中 - Storing data in arrays instead of database 使用 jQuery.data() 存储 WebSocket 连接句柄对象时出现问题 — 最好的做法是什么? - Problems when storing WebSocket connection handle objects using jQuery.data() — what's the best thing to do? 如何使用纯Java脚本下载S3对象数据(无节点) - How to download S3 object data using plain Javascript (no Node) 通过将对象数据存储在变量中来打印数据 - printing the data of objects by storing it in variables 什么是用于存储域数据的合适的reducer体系结构 - What's is the right reducer architecture for storing domain data Javascript:将数据存储在变量中。 初学者错误? - Javascript: Storing Data in Variables. Beginner error? 使用这种语法的原因是什么 (0, _.Em)(); - What's the reason for using such syntax (0, _.Em)();
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM