JSON - 根据json的索引显示数据

时间:2013-02-21 20:17:31

标签: javascript jquery json indexing

我正在尝试以项目符号的形式显示特定的json数据。每个 数据加入<li>,每个 标题 加入<p>并制作这些标题作为link。最后,请考虑点击 标题 的索引,在第二个<div>中显示相关的 内容 。我下面已经有了一些代码(还没有工作)。

HTML

<div id="page1">
    <ul id="courses"></ul>
</div>
<div id="page2">
    <p id="content"></p>
</div>

JS代码

var jsonString = '[{"chapter":"General","title":"News forum","content":"Text1"},
{"chapter":"CHAPTER 1","title":"1.1 Introduction","content":"Text2"},
{"chapter":"CHAPTER 1","title":"1.2 Main Idea","content":"Text3"},
{"chapter":"CHAPTER 2","title":"2.1 Architecture","content":"Text4"},
{"chapter":"CHAPTER 3","title":"3.1 Liter.overview","content":"Text5"}]';

var myData = JSON.parse(jsonString);

$(document).ready(function() {
    var $clist = $('#courses');
    for(var i in myData) {
        $('<li><h3>' +this.[i].chapter+ '</h3><p><a href="#page2" onclick="dContent(i)">' +this.title+ '</a></p></li>').appendTo($clist);
    }

    function dContent() {
        var $ccontent = $('#content');
        $(this.[i].content).appendTo($ccontent);
    }
});

预期结果:

- General
    News forum          // onclick display 'Text1' in <p id="content">
- CHAPTER 1
    1.1 Introduction    // onclick display 'Text2' in <p id="content">
    1.2 Main Idea       // onclick display 'Text3' in <p id="content">
- CHAPTER 2
    2.1 Architecture    // onclick display 'Text4' in <p id="content">
- CHAPTER 3
    3.1 Liter.overview  // onclick display 'Text5' in <p id="content">

任何帮助都将不胜感激。

更新:这是JSFIDDLE项目。

5 个答案:

答案 0 :(得分:1)

var jsonString = '[{"chapter":"General","title":"News forum","content":"Text1"},{"chapter":"CHAPTER 1","title":"1.1 Introduction","content":"Text2"},{"chapter":"CHAPTER 1","title":"1.2 Main Idea","content":"Text3"},{"chapter":"CHAPTER 2","title":"2.1 Architecture","content":"Text4"},{"chapter":"CHAPTER 3","title":"3.1 Liter.overview","content":"Text5"}]';
var myData = JSON.parse(jsonString);

var dContent = function(event) {
    $ccontent.html($(this).data('content'));
}

var $clist = $('#courses');
var $ccontent = $("#content");
var html = '';
var chapterList = [];

$clist.on('click', 'li', dContent);

$.each(myData, function(index, item) {
    if ($.inArray(item.chapter, chapterList) === -1) {
        chapterList.push(item.chapter);
        html += '<li data-content="'+ item.content +'"><h3>' + item.chapter + '</h3><p><a href="#page2">' + item.title + '</a></p></li>';
    }
    else {
        html += '<li data-content="'+ item.content +'"><p><a href="#page2">' + item.title + '</a></p></li>'
    }
});
$clist.html(html);

答案 1 :(得分:1)

我写了一个脚本来完成这项工作,包括将同一章中的项目放在一起。您可以看到demo fiddle here

我使用原生JavaScript进行大部分工作,除了$(a).on('click', ..$(document).ready的jQuery以确保兼容性。为什么这么久?因为我用DOM方法构建<ul>,而不是html字符串。这使得缓存和追加元素变得容易。最后,通过生成器函数添加内容。我这样做的方式意味着页面将使用稍多的内存,但您可以拥有任何字符串,该字符串在内容部分中显示的JavaScript中有效。您可能希望使用whitespace: pre-wrap;设置样式以按预期显示新行。

无论如何,这是代码

var jsonString = '[{"chapter":"General","title":"News forum","content":"Text1"},\
{"chapter":"CHAPTER 1","title":"1.1 Introduction","content":"Text2"},\
{"chapter":"CHAPTER 1","title":"1.2 Main Idea","content":"Text3"},\
{"chapter":"CHAPTER 2","title":"2.1 Architecture","content":"Text4"},\
{"chapter":"CHAPTER 3","title":"3.1 Liter.overview","content":"Text5"}]';
// the \ at line ends is to escape the new line in the string literal

var myData = JSON.parse(jsonString);

$(document).ready(function() {
    var courses_ul = document.getElementById('courses'), // cache elements
        content_elm = document.getElementById('content'),
        i, li, h3, p, a, // vars for loop
        chapters = {}, chap; // cache chapters
    for (i = 0; i < myData.length; ++i) {
        chap = myData[i].chapter; // shorthand since we'll use it a few times
        // make <p>, <a>
        p = document.createElement('p');
        a = document.createElement('a'); // could append <a> to <p> here if you want
        a.setAttribute('href', '#page2');
        a.appendChild(document.createTextNode(myData[i].title));
        // set up click
        $(a).on('click', (function (content) { // generator - will give scope to
            return function () { // this returned event listener.
                content_elm.innerHTML = '';
                content_elm.appendChild(document.createTextNode(content));
            };
        }(myData[i].content))); // chose `content` not `i` so no reliance on `myData`
        // now check cache if chapter exists -
        if (chap in chapters) { // retreive <li> for chapter from cache
            li = chapters[chap]; // from cache
            // append <p>, <a>
            li.appendChild(p).appendChild(a);
        } else { // if not in cache
            li = document.createElement('li'); // make a new <li>
            chapters[chap] = li; // and cache
            // make & append <h3>
            h3 = document.createElement('h3');
            h3.appendChild(document.createTextNode(chap));
            li.appendChild(h3);
            // append <p>, <a> and to <ul>
            courses_ul.appendChild(li).appendChild(p).appendChild(a);
        }
    }
});

答案 2 :(得分:0)

您的JSON结构无效。正确的结构如下:

[
    {
        "chapter": "General",
        "title": "News forum",
        "content": "Text1"
    },
    {
        "chapter": "CHAPTER 1",
        "title": "1.1 Introduction",
        "content": "Text2"
    },
    {
        "chapter": "CHAPTER 1",
        "title": "1.2 Main Idea",
        "content": "Text3"
    },
    {
        "chapter": "CHAPTER 2",
        "title": "2.1 Architecture",
        "content": "Text4"
    },
    {
        "chapter": "CHAPTER 3",
        "title": "3.1 Liter.overview",
        "content": "Text5"
    }
]

请注意,JSON结构中的逗号为3.1 Liter.overview","content":"Text5"},,此处失败

带代码的更新答案

var jsonString = '[{"chapter": "General","title": "News forum","content": "Text1"},{"chapter": "CHAPTER 1","title": "1.1 Introduction","content": "Text2"},{"chapter": "CHAPTER 1","title": "1.2 Main Idea", "content": "Text3"},{"chapter": "CHAPTER 2","title": "2.1 Architecture","content": "Text4"},{"chapter": "CHAPTER 3","title": "3.1 Liter.overview","content": "Text5"}]';

var myData = JSON.parse(jsonString);
$(document).ready(function() {
    function dContent() {
       $("#content").css("border","2px solid red").css("height","100px");
       $("#content").html($(this).data('value'));
    }
     $("#courses").on('click','li', dContent) 
    $.each(myData, function(index,item) { 
    $("#courses").append("<li class='li' data-value="+item.content+">"+item.chapter+"  <p>"+item.title+"</p></li>");

    })



});

DEMO ON JSFIDDLE

答案 3 :(得分:0)

this.[i].chapter应该是myData[i].chapter。实际上,这是一个语法错误。

然后你应该重新考虑你对this的其他用途是否正确。

答案 4 :(得分:0)

将它复制到你的JSFiddle并检查jQuery,将使它工作。

var jsonString = '[{"chapter":"General","title":"News forum","content":"Text1"},{"chapter":"CHAPTER 1","title":"1.1 Introduction","content":"Text2"},{"chapter":"CHAPTER 1","title":"1.2 Main Idea","content":"Text3"},{"chapter":"CHAPTER 2","title":"2.1 Architecture","content":"Text4"},{"chapter":"CHAPTER 3","title":"3.1 Liter.overview","content":"Text5"}]';

var myData = JSON.parse(jsonString);

$(document).ready(function() {
    var $clist = $('#courses');

    $.each(myData, function(i,o){
        $('<li><h3>' +o.chapter+ '</h3><p>' +
          '<a href="#page2" onclick="dContent(\''+o.content+'\')">' +
          o.title + '</a></p></li>').appendTo($clist);
    });

    window.dContent = function(content) {
        var $ccontent = $('#content');
        $ccontent.append(content);

    } 
});