将数据存储在DOM中 [英] Storing data in the DOM

查看:181
本文介绍了将数据存储在DOM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本书,我想要存储每本书的数据,例如

I have a list of books and I want to store data against each book e.g. Price, Quantity, id, catergory id, size, weight etc.

我正在通过将表示每本书的li元素扩展到列表中来存储所有这些内容。使用数据属性。这个数据可以直接用javascript。

I was looking at storing all this in the dom by extending the li elements representing each book in the list using data- attributes. This data could then be utilised directly with javascript.

但是我已经看到,访问数据属性在性能上很慢。另外我可以有同一本书的多个实例,所以在html中有一点关于膨胀的想法。

However I have read that accessing data- attributes is slow in a performance sense. In addition I can have multiple instances of the same book so am a little concerened about bloat in the html.

另一种方法是使用JS对象存储数据每本书。

An alternative would be to use a JS object to store data for each book.

所以我的问题是在前端,DOM或Javscript中存储数据的最佳做法是什么?

So my question is what is the best practice for storing data in the frontend, DOM or Javscript?

感谢提前

推荐答案

数据 - 属性通常用于更多一种获取数据到JavaScript中的方法(即从您的服务器端模板),以及一个用于存储数据的运行时间。一个更好的地方保持你的活动数据是一个JavaScript对象,特别是如果你将访问它或在脚本的生活中频繁地操作它。

The data- attributes are generally used more as a way to get data into your JavaScript (i.e. From your server-side template), and less a runtime place to store your data. A better place keep your active data is in a JavaScript object, especially if you will be accessing it or manipulating it frequently during the life of your script.

这更多使用MVC方法,数据存在于您的模型中,但可能在您的View中显示。因此,一些较新的MVC框架(如AngularJS)可以在两者之间提供自动双向绑定。

This is more in keeping with an MVC approach, where the data lives in your Model, but may be represented in your View. For this reason, some of the newer MVC frameworks like AngularJS provide automatic two-way binding between the two.

这篇关于将数据存储在DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆