0

I have a JSON file titled with many different attributes regarding books (author, desc, title etc). I am using JSON to load the content into a div and display only the title. My problem is I'm trying to make each title a link and display the rest of the content for that specific book in a separate div on the same page. Below is what I have so far. Whenever I try to reference anything after the click function my response it "undefined"

$.getJSON("data/data.json", function(data){
   var res = _.sortBy(data.books, function(item) { return item.name });
   _.each(res, function(item){ 
      $("#books").append("<p class='book'>"+item.name+"</p>");
   });
$(".book").click(function() {
 var clickedItem = $(this);
$("#details").append("<p>"+clickedItem.author+"</p>");
user2980869
  • 59
  • 2
  • 10

1 Answers1

0

You could store the details of each book in the data of the node. This way you can access it anytime..

$.getJSON("data/data.json", function(data){
    var res = _.sortBy(data.books, function(item) { return item.name });
    _.each(res, function(item){ 
        var book = $("<p class='book'>"+item.name+"</p>").data('details', item);
        $("#books").append(book);
    });

    $("#books").on('click', '.book', function() {
        var clickedItem = $(this),
            details = clickedItem.data('details');

        $("#details").html("<p>"+details.author+"</p>");
    });
});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317