【发布时间】:2019-02-28 19:47:32
【问题描述】:
我需要动态构建一个JSON。
JSON 如果不是动态的,则可以工作。
这是一个工作示例,但 "@id" 和 "name" 不是动态的:
var el_2 = document.createElement('script');
el_2.type = 'application/ld+json';
el_2.text = JSON.stringify({
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{
"@type": "ListItem",
"position": 1,
"item": {
"@id": "https://example.com/",
"name": "Home",
}
}, {
"@type": "ListItem",
"position": 2,
"item": {
"@id": "https://example.com/text_1",
"name": "Text_1",
}
}, {
"@type": "ListItem",
"position": 3,
"item": {
"name": "Text_2",
}
}
}]
});
document.querySelector('head').appendChild(el_2);
我需要让它动态化。
我使用jQuery’s each() 函数循环遍历面包屑的每个元素。
然后,我将元素压入数组:
var array_breadcrumb_text = [];
$('.region-breadcrumb .breadcrumb li').each(function(index, value) {
array_breadcrumb_text.push($(this).find("a").attr('href') + ' : ' + $(this).text());
// output of links and text is correct
console.log(array_breadcrumb_text[index]);
});
我不知道如何使用这个数组来构建 JSON。
通常,我使用foreach 循环,但由于我在JSON.stringify() 内,我不能使用foreach 循环,因为我有语法问题。
这是面包屑的 HTML 结构
<ol class="breadcrumb">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/text_1">Text_1</a>
</li>
<li class="active">
Text_2
</li>
</ol>
【问题讨论】:
标签: javascript arrays json each