在< div>发送一个对象纯JavaScript中的数据集

发布于 2025-02-09 02:55:55 字数 1161 浏览 1 评论 0原文

我正在尝试在DIV数据集中获取一个完整的对象,并在JavaScript中检索它。

这是我的代码的样子:

<div id="test"></div>

<script>
  var config = {
    "user-id": "test001",
    "approach": true,
    "product-id": "testproduct1"
  }

  var x = document.createElement('iframe');
  x.setAttribute("id", "wrapper");
  x.setAttribute("srcdoc", '<script src="test.js"><\/script><div data-config="' + config + '" id="myid"></div>');
  document.getElementById('test').appendChild(x);
</script>

这是在JavaScript文件中,我想从Data-config获取数据,

const info = document.querySelector('#myid').dataset.data-config;

但是,我获得[Object Object]也尝试了以下操作,并获得相同的结果

var test = document.getElementById('myid').getAttribute("data-config");

来发送正常数据属性正在工作很好:

<div data-approach ='+ config.approach+' id="myid"></div>

var test = document.getElementById('myid').getAttribute("data-approach");

什么结果是我的控制台中的true

如何发送完整的配置,以便我不需要一个一个一个拆开?

i am trying to get a complete object in a div dataset and retrieve it in JavaScript.

This how my code looks like:

<div id="test"></div>

<script>
  var config = {
    "user-id": "test001",
    "approach": true,
    "product-id": "testproduct1"
  }

  var x = document.createElement('iframe');
  x.setAttribute("id", "wrapper");
  x.setAttribute("srcdoc", '<script src="test.js"><\/script><div data-config="' + config + '" id="myid"></div>');
  document.getElementById('test').appendChild(x);
</script>

this is in the JavaScript file where I would like to get the data from data-config

const info = document.querySelector('#myid').dataset.data-config;

however, I get [object object] also tried the following, with the same result

var test = document.getElementById('myid').getAttribute("data-config");

to send a normal data attribute is working fine as such:

<div data-approach ='+ config.approach+' id="myid"></div>

var test = document.getElementById('myid').getAttribute("data-approach");

what results as true in my console.

how can I send the complete config so i don't need to take it apart one by one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫瑟鸿黎 2025-02-16 02:55:55

与json.stringify()设置。

let data = {} // any referance data;

const info = document.querySelector('#myid').dataset.config = 
JSON.stringify(data);

使用json.parse()获取数据。

let data = JSON.parse(document.querySelector('#myid').dataset.config)

To set with JSON.stringify().

let data = {} // any referance data;

const info = document.querySelector('#myid').dataset.config = 
JSON.stringify(data);

To get the data with JSON.parse().

let data = JSON.parse(document.querySelector('#myid').dataset.config)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文