jQuery 在 HTML5 数据属性中存储和检索 javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16223786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:43:47  来源:igfitidea点击:

store and retrieve javascript arrays into and from HTML5 data attributes

javascriptjqueryarraysparsinghtml5-data

提问by iurii

How can a javascript Arraybe stored in an HTML5 dataattribute?

如何将 javascriptArray存储在 HTML5data属性中?

I've tried every variation of JSON.stringifycation and escaping characters.

我已经尝试了JSON.stringify阳离子和转义字符的所有变体。

What is the precise method to store the array and retrieve it again?

存储数组并再次检索它的精确方法是什么?

note

笔记

I build the array with [ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]. I retrieve id="storageElement" data-storeIt="stuff"with $("#storageElement").data('storeit').

我用[ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]. 我检索id="storageElement" data-storeIt="stuff"$("#storageElement").data('storeit')

I can never seem to retrieve the data as a true Array, only an Arrayof characters.

我似乎永远无法将数据检索为 true Array,只能检索一个Array字符。

回答by iurii

It turned out that you could use the html escaped characters in the element dataattribute to have json-like array (encoded are quotes):

事实证明,您可以使用 elementdata属性中的 html 转义字符来获得类似 json 的数组(编码为引号):

<div id="demo" data-stuff='[&#34;some&#34;, &#34;string&#34;, &#34;here&#34;]'></div>

And then in javascript get it without any additional magic:

然后在 javascript 中获取它,无需任何额外的魔法:

var ar = $('#demo').data('stuff');

Check this fiddleout.

检查这个小提琴

Edited (2017)
You don't need to use html escaped characters in the dataattribute.

已编辑 (2017)
您不需要在data属性中使用 html 转义字符。

<div id="demo" data-stuff='["some", "string", "here"]'></div>

Check this new fiddleout.

检查这个新小提琴

回答by Grinn

It depends on what type of data you're storing in the array. If it's just strings (as it appears to be) and you have a character that you knowwill never be a part of your data (like the comma in my example below) then I would forget about JSON serialization and just use string.split:

这取决于您在数组中存储的数据类型。如果它只是字符串(因为它似乎),你有一个角色,你知道的永远不会是你的数据的一部分(如下面的示例所示的逗号),那么我会忘了JSON序列化,只是使用string.split:

<div id="storageElement" data-storeIt="stuff,more stuff"></div>

Then when retrieving:

然后在检索时:

var storedArray = $("#storageElement").data("storeIt").split(",");

It will handle a bit better than using JSON. It uses less characters and is less "expensive" than JSON.parse.

它会比使用 JSON 处理得更好一些。它使用更少的字符并且比JSON.parse.

But, if you must, your JSON implementation would look something like this:

但是,如果必须的话,您的 JSON 实现将如下所示:

<div id="storageElement" data-storeIt='["hello","world"]'></div>

And to retrieve:

并检索:

var storedArray = JSON.parse($("#storageElement").data("storeIt"));

Notice that in this example we had to use semi-quotes (') around the data-storeItproperty. This is because the JSON syntax requires us to use quotes around the strings in its data.

请注意,在此示例中,我们必须'data-storeIt属性周围使用半引号 ( ) 。这是因为 JSON 语法要求我们在其数据中的字符串周围使用引号。

回答by nullability

The HTML5 data attribute can store only strings, so if you want to store an array you will need to serialize it. JSON will work and it looks like you're on the right path. You just need to use JSON.parse()once you retrieve the serialized data:

HTML5 data 属性只能存储字符串,所以如果你想存储一个数组,你需要序列化它。JSON 将起作用,看起来您走在正确的道路上。您只需要在JSON.parse()检索序列化数据后使用:

var retrieved_string = $("#storageElement").data('storeit');
var retrieved_array = JSON.parse(retrieved_string);

Reviewing the api documentation, jQuery should try to automatically convert a JSON encoded string provided it is properly encoded. Can you give an example of the value you are storing?

查看api 文档,jQuery 应该尝试自动转换 JSON 编码的字符串,前提是它编码正确。你能举一个你存储的价值的例子吗?

Also note that HTML5 data attribute and jQuery .data()methods are two distinct things. They interact, but jQuery is more powerful and can store any data type. You could just store a javascript array directly using jQuery without serializing it. But if you need to have it in the markup itself as an HTML5 data attribute, then you are limited only to strings.

还要注意 HTML5 数据属性和 jQuery.data()方法是两个不同的东西。它们相互作用,但 jQuery 更强大,可以存储任何数据类型。您可以直接使用 jQuery 存储一个 javascript 数组,而无需对其进行序列化。但是,如果您需要将它作为 HTML5 数据属性包含在标记本身中,那么您只能使用字符串。

回答by Mateo Tibaquira

For the record, it didn't work with encoded entities for me, but seems that in order to be parsed as an object, the data attribute must be a well formed JSON object.

为了记录,它对我来说不适用于编码实体,但似乎为了被解析为对象,数据属性必须是格式良好的 JSON object

So I was able to use an object with:

所以我能够使用一个对象:

data-myarray="{&quot;key&quot;: &quot;value&quot;}"

or maybe just use single quotes:

或者只是使用单引号:

data-myobject='{"key1": "value1", "key2": value2}'

Time to have fun! :D

是时候玩得开心了!:D

回答by kayz1

You can store any object into node like that:

您可以像这样将任何对象存储到节点中:

$('#storageElement').data('my-array', ['a', 'b', 'c']);

var myArray = $('#storageElement').data('my-array');

回答by Henry

If using PHP do in PHP:

如果使用 PHP 在 PHP 中执行:

$arr_test = ['A','C','E'];
$coded = json_encode($arr_test);
// paste coded in data-atribute
print '<div class="funPlus" data-arr_diensten="'. $coded . '"></div>';

The HTML on inspect looks like:

检查中的 HTML 如下所示:

<div class="funPlus" data-arr_diensten="[&quot;A&quot;,&quot;C&quot;,&quot;E&quot;]"></div>

Now in javascript retrieve the array, but if it has only one value it returns as a string. So you have to test and fix this. If it is a string we have to remove the extra quotes. $(this) has to point to the object.

现在在 javascript 中检索数组,但如果它只有一个值,它将作为字符串返回。所以你必须测试并解决这个问题。如果它是一个字符串,我们必须删除额外的引号。$(this) 必须指向对象。

var arr_diensten = $(this).data("arr_diensten");
if (typeof arr_diensten == "string") arr_diensten = [arr_diensten.slice(1, -1)];
console.log(arr_diensten);