gpt4 book ai didi

javascript - 从 javascript 访问 json 元素

转载 作者:行者123 更新时间:2023-11-28 09:23:23 27 4
gpt4 key购买 nike

我有这个 JSON,它使用 i18next对于 i18n 一个使用 Blade 作为 templating engine 的网站:

"guide": {
"sections": {
"the-basics": {
"title": "The Basics",
"contents": [
{
"title": "Introduction",
"content": {"p1": "", "p2": "", "p3": ""}
},
{
"title": "A Chapter in the Zeitgeist Movement",
"content": {"p1": "", "p2": "", "p3": ""}
}
]
},
"setting-up-a-national-chapter": {
"title": "Setting up a National Chapter",
"contents": [
{
"title": "Gathering Volunteers & Social Media",
"content": {"p1": "", "p2": "", "p3": ""}
}
]
}
}
}

在我的 JavaScript 中,我尝试根据索引号访问内容列表。

这是我到目前为止所拥有的:

  // Load page
$('a.nav-link').on('click', function( event ) {
event.preventDefault();
var $this = $(this);
var section = $this.closest('ul').prev('h3').find('span[data-content]').data('content');
var subSection = $this.attr("data-content");
// we can now genrate the section content and push this into the tmpl.
blade.Runtime.loadTemplate("guide_section.blade", function(err, tmpl) {
tmpl({
'sections': {
'section': section,
'subsection': subSection
}
}, function(err, html) {
if(err) throw err;
console.log(html);
$('.mainarticle > .content').empty().html(html);
});
});
});

在我的模板中:

#guide_section
- var i = sections.section
- var c = sections.subsection
h5(data-i18n="guide.sections."+i+".title")=i
h4(data-i18n="guide.sections."+i+".contents.title")=c

上面的代码与jade的模板非常相似。

H5 工作正常,因为它返回标题,但我不确定如何返回内容列表的第 n 个元素。

例如:

h5(data-i18n="guide.sections."+i+".title")=i

渲染为

<h5 data-i18n="guide.sections.the-basics.title">the-basics</h5 

这是正确的,因为 i18next 会查找 translation.json 并根据 data-i18n 值设置正确的翻译,但是

data-i18n="guide.sections."+i+".contents.title"

渲染为

<h4 data-i18n="guide.sections.the-basics.contents[0]">0</h4

但在本例中,contents 有两个条目,例如:

[{
"title": "Introduction",
"content": {"p1": "", "p2": "", "p3": ""}
},{
"title": "A Chapter in the Zeitgeist Movement",
"content": {"p1": "", "p2": "", "p3": ""}
}]

那么如何更改我的脚本,以便通过提供索引,我可以访问 contents 列表的标题?

最佳答案

这有效,取自 http://i18next.com/pages/doc_features.html#objecttree ,所以在我的例子中“内容”是一个数组

ul.sub-section
- var content = t("guide.sections."+i+".contents", { returnObjectTrees: true });
- for(var c in content)
- var section_title = t(content[c].title)
li
a.nav-link(href="#" data-bind=""+c data-content=""+section_title data-i18n="guide.sections."+i+".contents.title")=t(content[c].title)

关于javascript - 从 javascript 访问 json 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14708398/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com