Reputation: 11
I tried to create a function which generates a link and added it to an element. But the .click function wont work. I dont even get an error, thats why I'm not sure if the function or the variable is wrong.
This is my javascript code:
$("#nwa1").click(function(){
var titel = document.getElementById("h1").innerHTML;
link = '';
link += 'nwa_' + titel + '.json'
$.getJSON(link, function(json){
aus = '';
aus += '<table border="1"><tr><th>Kcal</th><th>Eiweiß in g</th><th>Fett in g</th></tr>';
for (i = 0; i < json.werte.length; i++){
aus += '<td>' + json.werte[i].kcal + '</td>' + '<td>' + json.werte[i].eiweiß + '</td>' + '<td>' + json.werte[i].fett + '</td>';
}
aus += '</tr></table>';
$('#div2').html(aus);
})
})
And here is the html page:
<h4 id="nwa1">Nährwertangaben</h4>
<div id="div2" ></div>
The link i want to open with the function is nwa_falafel.json and 'falafel' is my h1-element.
Thank you, for trying to help!:)
Upvotes: 1
Views: 234
Reputation: 1392
This is an issue with the path to your JSON file. Try the (working) code below and check the console for to see if it is logging an error.
$("#nwa1").click(function()
{
alert('genau!');
$titel = document.getElementById("h1").innerHTML;
$link = '';
$link += 'nwa_' + $titel + '.json'
$.getJSON( $link, {
format: "json"
})
.fail(function() {
console.log( "error" );
})
.done(function( data ) {
console.log("done");
console.log(data.werte);
aus = '';
aus += '<table border="1"><tr><th>Kcal</th><th>Eiweiß in g</th><th>Fett in g</th></tr>';
$.each( data.werte, function( i, item ) {
aus += '<td>' + item.kcal + '</td>' + '<td>' + item.eiweiß + '</td>' + '<td>' + item.fett + '</td>';
});
aus += '</tr></table>';
$('#div2').html(aus);
});
});
I added some colors my side just for emphasis:
So if you are getting an error check the location /path to your JSON file as the code works fine.
Upvotes: 1