[英]How to assign an object to a html element?
我有一个对象数组作为来自服务器的响应,我正在尝试将该响应内的对象数组分配给 html 元素。 我试过data-code="${JSON.stringify(item.ObjectProp)}"
。
但是我在控制台记录它时得到 [Object object] 或{[
(数组的前 2 个元素)。
一些代码示例:
async getRequestFunction() {
const response = await fetch(url);
const data = await response.json();
data.InvoiceList.forEach(item => {
table.innerHTML += `<div data-code="${item.Lines}">${item.Name}</div>`;
}
console.log(document.querySelector('div').getAttribute('data-code'));
// Output is either [Object object] or '{[', depending if I JSON.stringify the
`item.Lines` or not.
}
我还在 getAttribute 行上尝试过JSON.parse
。 我得到的错误是: Unexpected token o in JSON at position 1 at JSON.parse
编辑:发现问题出在这里:
<div class="table-sent-item" data-code="[{" article":"","barcode":null,"code":"00160047","name":"imprimanta="" pos="" orderman="" srp-330ii="" serial="" ethernet=""}]"></div>
在对其进行数据编码之后, [{
用双引号引起来,因此 getAttribute 不再是 go 。
基本上,我必须用单引号替换[{
之后的所有双引号。
EDIT2:我已经用这样的单引号替换了 json object 中的双引号: data-code="${JSON.stringify(item.Lines).replace(/"/g, "'")}"
。并且然后JSON.parse
结果(并反向替换引号)。当数组中只有一个 object 时,它工作得很好。
但是当数据代码中的数组中有多个对象时,我得到 JSON.parse 错误。 Unexpected string in JSON
。
/* NEW EDIT */
var data = [1,2,3] var str = JSON.stringify(data) document.body.innerHTML = `<div id="box" data-code=${str}></div>` alert(document.querySelector('#box').dataset.code) console.log(JSON.parse(document.querySelector('#box').dataset.code))
问题出在 JSON 值中,其中包含double 'single quotes'
。 DOM 将其识别为以"double quotes"
结尾。 将其替换为另一个符号replace(/'/g, "\~")
。 然后反向更换了output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.