将 JSON 对象存储在 HTML jQuery 的 data 属性中
我使用 data-
方法在 HTML 标记中存储数据,如下所示:
<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>
然后我在回调中检索数据,如下所示:
$(this).data('imagename');
效果很好。我所坚持的是尝试保存对象而不是仅保存它的属性之一。我尝试这样做:
<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>
然后我尝试像这样访问 name 属性:
var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);
日志告诉我未定义
。所以看起来我可以在 data-
属性中存储简单的字符串,但我无法存储 JSON 对象...
我也尝试过使用这个语法,但没有运气:
<div data-foobar='{"foo":"bar"}'></div>
任何想法如何使用 data-
方法在 HTML 标记中存储实际对象?
I am storing data using the data-
approach in a HTML tag like so:
<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>
I am then retrieving the data in a callback like this:
$(this).data('imagename');
That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:
<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>
Then I tried to access the name property like this:
var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);
The log tells me undefined
. So it seems like I can store simple strings in the data-
attributes but I can't store JSON objects...
I've also tried to use this kid of syntax with no luck:
<div data-foobar='{"foo":"bar"}'></div>
Any idea on how to store an actual object in the HTML tag using the data-
approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
实际上,您的最后一个示例:
似乎运行良好(请参阅http://jsfiddle.net/GlauberRocha/Q6kKU/)。
好处是 data- 属性中的字符串会自动转换为 JavaScript 对象。相反,我认为这种方法没有任何缺点!一个属性足以存储一整套数据,可以通过对象属性在 JavaScript 中使用。
(注意:为了使 data- 属性自动指定为 Object 类型而不是 String 类型,您必须小心编写有效的 JSON,特别是将键名称括在双引号中)。
Actually, your last example:
seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).
The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don't see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.
(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).
而不是将其嵌入到文本中,只需使用
$('#myElement').data('key',jsonObject);
它实际上不会存储在 html 中,但如果您使用jquery.data,无论如何都是抽象的。
要获取 JSON,不解析它,只需调用:
如果您获取的是
[Object Object]
而不是直接 JSON,只需通过数据键访问您的 JSON:instead of embedding it in the text just use
$('#myElement').data('key',jsonObject);
it won't actually be stored in the html, but if you're using jquery.data, all that is abstracted anyway.
To get the JSON back don't parse it, just call:
If you are getting
[Object Object]
instead of direct JSON, just access your JSON by the data key:这对我来说就是这样的。
对象
设置
使用 encodeURIComponent() 并设置为属性:
Get
要将值作为对象获取,请使用 decodeURIComponent(),属性值:
This is how it worked for me.
Object
Set
Encode the stringified object with encodeURIComponent() and set as attribute:
Get
To get the value as an object, parse the decoded, with decodeURIComponent(), attribute value:
存储序列化数据的许多问题可以通过转换序列化字符串 到 base64。
Base64 字符串几乎可以在任何地方被接受,没有什么大惊小怪的。
看一下:
根据需要进行转换。
A lot of problems with storing serialized data can be solved by converting the serialized string to base64.
A base64 string can be accepted just about anywhere with no fuss.
Take a look at:
Convert to/from as needed.
有一种更好的方法在 HTML 中存储 JSON:
HTML
JavaScript
There's a better way of storing JSON in the HTML:
HTML
JavaScript
将
window.btoa
和window.atob
结合使用JSON.stringify 和 JSON.parse。
- 这适用于包含单引号的字符串
对数据进行编码:
对数据进行解码:
这是稍后如何构造和解码数据的示例
与点击事件。
构造 html 并对数据进行编码:
在点击事件处理程序中解码数据:
Combine the use of
window.btoa
andwindow.atob
together withJSON.stringify
andJSON.parse
.- This works for strings containing single quotes
Encoding the data:
Decoding the data:
Here is an example of how the data is constructed and decoded later
with the click event.
Construct the html and encode the data:
Decode the data in the click event handler:
对我来说,它是这样工作的,因为我需要将它存储在模板中...
For me it work like that, as I need to store it in template...
对我来说,诀窍是在键和值周围添加双引号。如果您使用像
json_encode
这样的 PHP 函数,将为您提供一个 JSON 编码字符串以及如何正确编码您的字符串的想法。如果字符串正确编码为 json,
jQuery('#elm-id').data('datakey')
将返回字符串的对象。根据 jQuery 文档:(http://api.jquery.com/jquery.parsejson/)
传入格式错误的 JSON 字符串会导致引发 JavaScript 异常。例如,以下都是无效的 JSON 字符串:
"{test: 1}"
(test
周围没有双引号)。"{'test': 1}"
('test'
使用单引号而不是双引号)。"'test'"
('test'
使用单引号而不是双引号)。".1"
(数字必须以数字开头;"0.1"
有效)。"undefined"
(undefined
不能用 JSON 字符串表示;但是null
可以)。"NaN"
(NaN
不能用 JSON 字符串表示;无穷大的直接表示也是 nThe trick for me was to add double quotes around keys and values. If you use a PHP function like
json_encode
will give you a JSON encoded string and an idea how to properly encode yours.jQuery('#elm-id').data('datakey')
will return an object of the string, if the string is properly encoded as json.As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)
Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:
"{test: 1}"
(test
does not have double quotes around it)."{'test': 1}"
('test'
is using single quotes instead of double quotes)."'test'"
('test'
is using single quotes instead of double quotes).".1"
(a number must start with a digit;"0.1"
would be valid)."undefined"
(undefined
cannot be represented in a JSON string;null
, however, can be)."NaN"
(NaN
cannot be represented in a JSON string; direct representation of Infinity is also n这段代码对我来说工作得很好。
使用 btoa 编码数据
,然后使用 atob 解码
This code is working fine for me.
Encode data with btoa
And then decode it with atob
使用 记录的 jquery .data(obj) 语法 允许您将对象存储在DOM 元素。检查元素不会显示
data-
属性,因为没有为对象的值指定键。但是,可以使用.data("foo")
通过键引用对象内的数据,也可以使用.data()
返回整个对象。因此,假设您设置了一个循环并且
result[i] = { name: "image_name" }
:Using the documented jquery .data(obj) syntax allows you to store an object on the DOM element. Inspecting the element will not show the
data-
attribute because there is no key specified for the value of the object. However, data within the object can be referenced by key with.data("foo")
or the entire object can be returned with.data()
.So assuming you set up a loop and
result[i] = { name: "image_name" }
:由于某种原因,接受的答案仅在页面上使用一次时才对我有用,但就我而言,我试图保存页面上许多元素的数据,并且除了第一个元素之外的所有元素上的数据都以某种方式丢失了。
作为替代方案,我最终将数据写入 dom,并在需要时将其解析回来。也许它的效率较低,但对于我的目的来说效果很好,因为我实际上是在对数据进行原型设计,而不是为了生产而编写它。
为了保存我使用的数据:
然后读回数据与接受的答案相同,即:
如果我要使用 Chrome 的调试器检查元素,这样做也会使数据出现在 dom 中。
For some reason, the accepted answer worked for me only if being used once on the page, but in my case I was trying to save data on many elements on the page and the data was somehow lost on all except the first element.
As an alternative, I ended up writing the data out to the dom and parsing it back in when needed. Perhaps it's less efficient, but worked well for my purpose because I'm really prototyping data and not writing this for production.
To save the data I used:
To then read the data back is the same as the accepted answer, namely:
Doing it this way also made the data appear in the dom if I were to inspect the element with Chrome's debugger.
.data()
适用于大多数情况。我唯一遇到的问题是 JSON 字符串本身有单引号。我找不到任何简单的方法来解决这个问题,所以采用了这种方法(我使用 Coldfusion 作为服务器语言):.data()
works perfectly for most cases. The only time I had a problem was when the JSON string itself had a single quote. I could not find any easy way to get past this so resorted to this approach (am using Coldfusion as server language):作为记录,我发现以下代码有效。它使您能够从数据标记中检索数组,推送新元素,然后以正确的 JSON 格式将其存储回数据标记中。因此,如果需要,可以再次使用相同的代码向数组添加更多元素。我发现
$('#my-data-div').attr('data-namesarray', names_string);
正确存储了数组,但是$('#my-data- div').data('namesarray', names_string);
不起作用。For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that
$('#my-data-div').attr('data-namesarray', names_string);
correctly stores the array, but$('#my-data-div').data('namesarray', names_string);
doesn't work.});
});
我在 https://oblik.dev/utilities/config/ 中找到了更好的方法
基本上他们所做的是有一个解析器从类似 json 的对象不带双引号:
更多示例:
我希望看到类似这种标准化格式的东西
I found a better way in https://oblik.dev/utilities/config/
Basically what they do is have a parser from-to json-like objects without double quotes:
More examples:
I would like to see something like this format standartized