Is it bad to add JSON on HTML data attribute?

前端 未结 5 1741
花落未央
花落未央 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:46

    Say you want to save the object var dataObj = { foo: 'something', bar: 'something else' }; to an html data attribute.

    Consider first stringifying the object such that we have var stringifiedDataObj = JSON.stringify(dataObj);

    Then you can use jQuery to set the stringifiedDataObj as the data attribute e.g. with the jQuery.data() API

提交回复
热议问题