如何在JSON中加载对象内部的数组元素

How do I load the elements of an array inside of an object in JSON?

本文关键字:对象 内部 数组元素 加载 JSON      更新时间:2023-11-28

我以前问过一个类似(但不同)的问题。

从那以后,我改变了处理这个问题的方式。

这是我的JSON文件。

到目前为止,这是我的javascript:

$(document).ready(function () {
    var loadArticle = function (articleID, articleH) {
        var article = $("#article").clone();
        var thelist = '<dl id="article' + articleID + 'sections"></dl>';
        $(article).attr("id", "article" + articleID);
        $(article).append(articleH);
        $(article).html(thelist);
        return article;
    }
    var loadSection = function (articleID, sectionID, sectionContent) {
        var section = "#article" + articleID + "sections";
        $(section).append("<dt>Section " + sectionID + "</dt>");
        $(section).append("<dd>" + sectionContent + "</dd>");
        return section;
    }
    var loadConstitution = function (d) {
        $.each(d, function (i) {
            var articleID = i + 1;
            var articleH = "<p class='lead' id='article" + articleID + "'><strong>Article " + articleID + "</strong></p>";
            $("#constitutionHolder").append(loadArticle(articleID, articleH));
            //$.each(d.sections, function(j){
            //  var sectionID = j + 1;
            //  var theSection = d.sections[j];
            //$("#article" + articleID + "sections").append(articleID, sectionID, mySection);
            //})
        })
    }
    $.getJSON('data/stuff.json', loadConstitution);
})

基本上,我遍历每个数据点,并用id="article1"(或文章的编号)创建一个新的<div>。然后,由于每个文章对象都填充了一个"sections"数组,因此我需要访问该数组中的数据,并将其附加到我拥有的<dl></dl>中。

在我的HTML中,这就是我的.clone()ing:

<div id="constitutionHolder">
    <div class="alert text-black" id="article">
        <p class="lead" id="articleHeader"><strong>Article 1</strong>
        </p>
        <dl id="sectionList"> <dt id="article_section">Section 1</dt>
            <dd id="article_sectionINFO">this stuff belongs to section 1</dd>
        </dl>
    </div>
</div>

到目前为止,我有两个问题:

  1. $(article).append(articleH);不工作

  2. 我无法将这些部分加载到sectionList中。

我该如何解决这个问题?

有很多方法可以实现这一点,但下面是一个您可以修改以适合您的应用程序的示例:http://jsfiddle.net/DgU3w/.(注意,我去掉了一些细节,试图理解这个问题)

我在你的例子中注意到了一些事情:

  • loadArticle()否定了以下语句的一些工作:$(article).html(thelist);
  • loadArticle()克隆一个HTML块,但随后会附加与克隆的元素相匹配的新元素
  • 包装jQuery对象(例如$(jQueryObj))没有坏处,但也没有必要
  • 某些ID已初始化为唯一值,但其他ID则未初始化