Skip to content Skip to sidebar Skip to footer

How To Display A Second Json Element In Javascript?

I'm trying to set up a newsletter which gets its contents from a JSON file with a number of articles consisting of a title and a text. Using JavaScript, I want the HTML page to dis

Solution 1:

This is quite easy to do with jQuery.

See here for a working fiddle: http://jsfiddle.net/manishie/pk7264u6/

html:

<body><divid="showData"></div></body>

javascript:

functiongetData() {
    var html = '';

    for(i = 0; i < article.length; i++) {
        html += "<li data-text='" + "'>" + article[i].title.link(article[i].text) + "</li>";
    }
    $('#showData').html('<ul>' + html + '</ul>');

    // Use jQuery 'on' to run code when any Anchor tag inside the #showData div is clicked.
    $('#showData').on('click', 'a', function(e) {

        // remove any previously displayed text (in divs with the .text class)
        $('#showData .text').remove();    

        // after the current element (the anchor tag that was clicked) add a new div with the class .text.  Inside that div, display the href attribute of the anchor tag that was clicked.
        $(this).after('<div class="text">' + $(this).attr('href') + '</div>');

        // disable normal anchor handling so you don't get taken to a non-existent page.
        e.preventDefault();    

    });

}

// Use jQuery $(document).ready to make sure the DOM is loaded before you run anything (http://learn.jquery.com/about-jquery/how-jquery-works/) instead of the onLoad in body.
$(document).ready(function() {
    getData();
});

Post a Comment for "How To Display A Second Json Element In Javascript?"