包含json的data属性中的单引号 [英] Single quotes in data attribute containing json
问题描述
化妆品问题: 我有一个html元素,其中包含一些嵌入式图像的可能尺寸,这些尺寸存储为:
Cosmetic question: I have a html element containing possible dimensions for some embedded images, these are stored as:
<div class="inside" data-dimensions='{ "s-x": 213, "s-y": 160, "m-x": ...
我得到了数据维度,并使用jQuery.parseJSON(jQuery.data("dimensions"))进行了很好的解析,并且紧跟着jQuery的文档.
I get out the data-dimension and parse with jQuery.parseJSON(jQuery.data("dimensions")) all fine and closely following the jquery's doc.
但是,我习惯将所有html属性封装在双引号中:
However I'm used to encapsulate all my html attributes inside double quotes:
<div class="inside" data-dimensions="{ 's-x': 213, 's-y': 160, 'm-x': ...
但是随后我得到了格式错误的json异常.有什么方法可以让我服从自己强加的双引号html属性"法则?
But then I get a malformed json exception. Are there ways so i can obey my self imposed "double quoted html attributes" law?
推荐答案
您可以使用"
代替"
.但是引用狂欢很可怕(在HTML中比在PHP中甚至更多),因此最好对HTML属性进行单引号.
You can use "
instead of "
. But quoting orgies are horrible (in HTML even more than in PHP) so better go with single-quoting your html attributes.
顺便说一句,您不需要使用.parseJSON
-如果data-
属性以{
开头,jQuery会自动执行此操作(实际上,它更复杂-这是它用来测试是否应解析为的正则表达式) JSON:^(?:\{.*\}|\[.*\])$
).
BTW, you do not need to use .parseJSON
- jQuery does that automatically if the data-
attribute starts with {
(actually, it's more complex - here's the regex it uses to test if it should be parsed as JSON: ^(?:\{.*\}|\[.*\])$
).
这篇关于包含json的data属性中的单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!