将 JSON 对象存储在 HTML jQuery 中的数据属性中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8542746/
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-27 10:40:06  来源:igfitidea点击:

Store JSON object in data attribute in HTML jQuery

jqueryhtmljson

提问by zumzum

I am storing data using the data-approach in a HTML tag like so:

我正在使用data-HTML 标记中的方法存储数据,如下所示:

<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:

然后我尝试像这样访问 name 属性:

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...

日志告诉我undefined。所以看起来我可以在data-属性中存储简单的字符串,但我不能存储 JSON 对象......

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?

关于如何使用该data-方法在 HTML 标记中存储实际对象的任何想法?

回答by Nicolas Le Thierry d'Ennequin

Actually, your last example:

实际上,你的最后一个例子:

<div data-foobar='{"foo":"bar"}'></div>

seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).

似乎运行良好(参见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.

好消息是 data- 属性中的字符串会自动转换为 JavaScript 对象。相反,我认为这种方法没有任何缺点!一个属性足以存储一整套数据,准备通过对象属性在 JavaScript 中使用。

(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).

(注意:为了让 data- 属性自动指定为 Object 而不是 String 类型,您必须小心编写有效的 JSON,尤其是将键名括在双引号中)。

回答by nathan gonzalez

instead of embedding it in the text just use $('#myElement').data('key',jsonObject);

而不是将其嵌入到文本中,只需使用 $('#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.

它实际上不会存储在 html 中,但是如果您使用的是 jquery.data,则无论如何都将其抽象化。

To get the JSON back don't parse it, just call:

要取回 JSON不要解析它,只需调用:

var getBackMyJSON = $('#myElement').data('key');

If you are getting [Object Object]instead of direct JSON, just access your JSON by the data key:

如果您要获取[Object Object]而不是直接 JSON,只需通过数据键访问您的 JSON:

var getBackMyJSON = $('#myElement').data('key').key;

回答by Sathvik reddy Gaddam

This is how it worked for me.

这就是它对我的工作方式。

Object

目的

var my_object ={"Super Hero":["Iron Man", "Super Man"]};

Set

Encode the stringified object with encodeURIComponent()and set as attribute:

使用encodeURIComponent()对字符串化对象进行编码并设置为属性:

var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);

Get

得到

To get the value as an object, parse the decoded, with decodeURIComponent(), attribute value:

要获取作为对象的值,请使用decodeURIComponent()解析解码后的属性值:

var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));

回答by Dan

A lot of problems with storing serialized data can be solved by converting the serialized stringto base64.

通过将序列化字符串转换为base64可以解决存储序列化数据的许多问题。

A base64 string can be accepted just about anywhere with no fuss.

几乎可以在任何地方接受 base64 字符串,而无需大惊小怪。

Take a look at:

看一眼:

The WindowOrWorkerGlobalScope.btoa()method creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

WindowOrWorkerGlobalScope.btoa()方法从 String 对象创建一个 base-64 编码的 ASCII 字符串,其中字符串中的每个字符都被视为一个二进制数据字节。

The WindowOrWorkerGlobalScope.atob()function decodesa string of data which has been encoded using base-64 encoding.

WindowOrWorkerGlobalScope.atob()函数对使用 base-64 编码的数据字符串进行解码

Convert to/from as needed.

根据需要转换为/从。

回答by molokoloco

For me it work like that, as I need to store it in template...

对我来说它是这样工作的,因为我需要将它存储在模板中......

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

回答by George Donev

The 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 propery encode yours.

我的诀窍是在键和值周围添加双引号。如果你使用像 json_encode 这样的 php 函数会给你一个 json 编码的字符串和一个如何对你的字符串进行编码的想法。

jQuery('#elm-id').data('datakey')will return an object of the string, if the string is properly encoded as json.

如果字符串正确编码为 json,jQuery('#elm-id').data('datakey')将返回字符串的对象。

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

根据 jQuery 文档:(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:

传入格式错误的 JSON 字符串会导致抛出 JavaScript 异常。例如,以下都是无效的 JSON 字符串:

  1. "{test: 1}"(test does not have double quotes around it).
  2. "{'test': 1}"('test' is using single quotes instead of double quotes).
  3. "'test'"('test' is using single quotes instead of double quotes).
  4. ".1"(a number must start with a digit; "0.1" would be valid).
  5. "undefined"(undefined cannot be represented in a JSON string; null, however, can be).
  6. "NaN"(NaN cannot be represented in a JSON string; direct representation of Infinity is also n
  1. “{test: 1}”(测试周围没有双引号)。
  2. "{'test': 1}"('test' 使用单引号而不是双引号)。
  3. “'test'”('test' 使用单引号而不是双引号)。
  4. “.1”(数字必须以数字开头;“0.1”有效)。
  5. “未定义”(未定义不能在 JSON 字符串中表示;但是可以为 null)。
  6. “NaN”(NaN 不能用 JSON 字符串表示;Infinity 的直接表示也是 n

回答by Wayne

Combine the use of window.btoaand window.atobtogether with JSON.stringifyand JSON.parse.

window.btoaandwindow.atobJSON.stringifyand结合使用JSON.parse

- This works for strings containing single quotes

- 这适用于包含单引号的字符串

Encoding the data:

编码数据:

var encodedObject = window.btoa(JSON.stringify(dataObject));

Decoding the data:

解码数据:

var dataObject = JSON.parse(window.atob(encodedObject));


Here is an example of how the data is constructed and decoded later with the click event.

这是稍后如何使用单击事件构造和解码数据的示例。

Construct the html and encode the data:

构造html并对数据进行编码:

var encodedObject = window.btoa(JSON.stringify(dataObject));

"<td>" + "<a class='eventClass' href='#' data-topic='" + encodedObject + "'>" 
+ "Edit</a></td>"

Decode the data in the click event handler:

解码单击事件处理程序中的数据:

$("#someElementID").on('click', 'eventClass', function(e) {
            event.preventDefault();
            var encodedObject = e.target.attributes["data-topic"].value;
            var dataObject = JSON.parse(window.atob(encodedObject));

            // use the dataObject["keyName"] 
}

回答by Vishal Patel

!DOCTYPE html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$("#btn1").click(function()
{
person = new Object();
person.name = "vishal";
person.age =20;
    $("div").data(person);
});
  $("#btn2").click(function()
{
    alert($("div").data("name"));
});

});

});

</script>
<body>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>
<div></div>
</body>


</html>

Anser:-Attach data to selected elements using an object with name/value pairs.
GET value using object propetis like name,age etc...

回答by Hp Sharma

This code is working fine for me.

这段代码对我来说很好用。

Encode data with btoa

使用 btoa 编码数据

let data_str = btoa(JSON.stringify(jsonData));
$("#target_id").attr('data-json', data_str);

And then decode it with atob

然后用atob解码

let tourData = $(this).data("json");
tourData = atob(tourData);

回答by user2069751

Using the documented jquery .data(obj) syntaxallows 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().

使用记录的 jquery .data(obj) 语法允许您在 DOM 元素上存储对象。检查元素不会显示data-属性,因为没有为对象的值指定键。但是,对象内的数据可以通过键引用,.data("foo")或者整个对象可以用 返回.data()

So assuming you set up a loop and result[i] = { name: "image_name" }:

因此,假设您设置了一个循环并且result[i] = { name: "image_name" }

$('.delete')[i].data(results[i]); // => <button class="delete">Delete</delete>
$('.delete')[i].data('name'); // => "image_name"
$('.delete')[i].data(); // => { name: "image_name" }