在HTML数据属性上添加JSON不好吗? [英] Is it bad to add JSON on HTML data attribute?

查看:86
本文介绍了在HTML数据属性上添加JSON不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于HTML data 属性允许添加任何自定义数据,因此我想知道是否包含一组 JSON 列表为数据属性?然后,通过 getAttribute(data-> css)可以轻松访问 JSON 事实上,我的问题是:是否标准,高效和合理地添加一大组数据一个 HTML 属性?



例如

 < div data-x =大型JSON数据集id =x> 

或者大量的JSON数据必须存储在< script> 标记,并且 HTML 属性对于大型数据集来说并不合适,即使对于 data 属性。

解决方案

不是将所有内容都存储在数据属性中,而是使用标识符来访问数据。



例如,您可以这样做:

  var myBigJsonObj = {
data1:{//很多数据},
data2:{//很多数据}

};

然后你有这样的html:

 < div data-dataId =data1id =x> 

您可以使用jquery获取现在的数据:

  var dataId = $('#x')。attr('data-dataId'); 

var myData = myBigJsonObj [dataId];

这是最好的方法。

Since HTML data attribute allows adding any custom data, I wonder if it is a good idea to include a set of JSON list as a data attribute? Then, the corresponding JSON can be easily accessed by JavaScript events with getAttribute("data-x").

In fact, my question is that: Is it standard, efficient, and reasonable to add a large set of data to a HTML attribute?

For example

<div data-x="A LARGE SET OF JSON DATA" id="x">

Or large set of JSON data must be stored within <script> tag, and a HTML attribute is not a right place for large set of data, even for data attribute.

解决方案

Instead of storing everything in the data attribute you could use an identifier to access the data.

So for example you could do this :

var myBigJsonObj = { 
                      data1 : { //lots of data}, 
                      data2 : { //lots of data}                   

                   };

and then you had some html like so :

<div data-dataId="data1" id="x">

You can use jquery to get the data now like so :

var dataId = $('#x').attr('data-dataId');

var myData = myBigJsonObj[dataId];

This is the best approach imho.

这篇关于在HTML数据属性上添加JSON不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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