Is it bad to add JSON on HTML data attribute?

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

    While there's nothing to stop you embedding a long string of JSON in a data attribute, arguably the more "correct" way of doing it would be to add one data attribute per property of the JSON data. eg:

    Javascript:

    var dataObj = { foo: 'something', bar: 'something else' }
    

    HTML:

    This way each piece of data in the JSON object corresponds to a separate, independently-accessible piece of data attached to the DOM element.

    Bear in mind that either way you'll need to escape the values you're inserting into the HTML - otherwise stray " characters will break your page.

提交回复
热议问题