Is it bad to add JSON on HTML data attribute?

前端 未结 5 1752
花落未央
花落未央 2021-01-31 16:05

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?

5条回答
  •  天命终不由人
    2021-01-31 16:55

    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 :

    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.

提交回复
热议问题