I am getting in JSON data, I am using dom to display the data, I want to embed a link to each search result displayed which when clicked passes that instance of data to another <div> block and display that result.
My HTML code is:
<html>
<body>
<div id:block 1 >
<div id:block 2>
<div id:block 3>
</body>
My JavaScript function is:
function addBooks(data) { // the data is a list of JSON objects
var listdiv = document.createElement('li');
listdiv.setAttribute('id', 'gBookListDiv');
listdiv.innerHTML = ("Books Found:");
parent.appendChild(listdiv);
for(i = 0; i < data.length; i++) {
//create each list item
var listItem = document.createElement('li');
var link = document.createElement('a');
listItem.setAttribute('id', 'gBookListItem');
parent.appendChild(listItem);
link.setAttribute('href', '#');
link.setAttribute('onclick', 'displayBook(data[i])');
listItem.appendChild(link);
}
}
function displayBook(bookData) {
alert(bookData.title);
if(document.getElementById("block2").style.display == "block") {
document.getElementById("block2").style.display = "none";
document.getElementById("block3").style.display = "block";
}
var headerTitle = document.getElementById('book-profile-title-header');
headerTitle.innerHTML = bookData.title;
var title = document.getElementById('book-profile-pic');
headerTitle.innerHTML = bookData.title;
}
For some reason, I am not able to pass the instance of data to the displayBook function.
This is the error I get on Chrome
Uncaught ReferenceError: data is not defined
The problem lies in this code:
The handler runs in the global context so
datais not defined there. Use a real function instead:The self-executing function around it is necessary to create a separate
iin each iteration.