javascript - HTML dataset - how to put object? data-x={} - Stack Overflow

HTML:<a data-test="{a: 1}">test<a>But in Chrome Console:> document.querySel

HTML:

<a data-test="{a: 1}">test</a>

But in Chrome Console:

> document.querySelector('a').dataset.test
< "{a: 1}"

typeof document.querySelector('a').dataset.test
"string"

I expected:

> document.querySelector('a').dataset.test
< {a: 1}

typeof document.querySelector('a').dataset.test
"object"

How can I write this HTML? (Without javascript)

HTML:

<a data-test="{a: 1}">test</a>

But in Chrome Console:

> document.querySelector('a').dataset.test
< "{a: 1}"

typeof document.querySelector('a').dataset.test
"string"

I expected:

> document.querySelector('a').dataset.test
< {a: 1}

typeof document.querySelector('a').dataset.test
"object"

How can I write this HTML? (Without javascript)

Share Improve this question edited Nov 15, 2020 at 19:36 vsync 131k59 gold badges340 silver badges423 bronze badges asked Nov 10, 2019 at 6:18 ebyteebyte 1,5173 gold badges22 silver badges36 bronze badges 1
  • Wele to Stack Overflow. I have removed the Chinese text from the question because this is an English-only site. – adiga Commented Nov 10, 2019 at 6:33
Add a ment  | 

3 Answers 3

Reset to default 4

You can write your HTML as the following.

<a data-test='{"a": 1}'>test</a>

And then in your script

console.log(JSON.parse(document.querySelector('a').dataset.test));

The output will be

{a: 1}

You just can use JSON.parse(string object).

var x = JSON.parse(document.querySelector('a').dataset.test);

console.log(x);

Editted: Please make sure that your object attribute in your <a> tag is a valid JSON. It should be <a data-test='{"a": 1}'>test</a>

It's not possible. A dataset item of an element can only contain a string, nothing else - after all, it's meant to be representable directly in the HTML, and the HTML is a string.

Either set the dataset item in JSON format and parse it later:

<a data-test='{"a": 1}'>test</a>

(note the double quotes around the key, as required by JSON)

const a = document.querySelector('a');
a.dataset.test = JSON.stringify({ a: 1 });

const test = JSON.parse(a.dataset.test);
console.log(test);
console.log(typeof test);
<a>test</a>

Or associate the element with its data some other way, perhaps with a Map whose keys are the elements, and values are the associated objects (if that's an option):

const map = new Map();
const a = document.querySelector('a');
map.set(a, { a: 1 });

const result = map.get(a);
console.log(result);
console.log(typeof result);
<a>test</a>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744713330a4589471.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信