Reputation: 99
I've created a menu from a jquery script. The script parses a json response file and creates the menu. That works. However, the menu then links to a URL. I don't want it to link to the URL, but rather get the json response from that URL and parse it. I've tried and no matter what, it always follows the URL. Here is what I have so far:
jQuery Menu creation (working):
<script>
$.getJSON('https://example.com/api/products/GetProductList/', function(data) {
var output = '<div class="panel panel-default">';
for (var i in data.Categories) {
output += '<div class="panel-heading '+data.Categories[i].category_id +'"><a data-toggle="collapse" data-parent="#accordion" href="#' + data.Categories[i].category_id + '-products">';
output += data.Categories[i].Category + '</a></div>';
output += '<div id="' + data.Categories[i].category_id + '-products" class="panel-collapse collapse"><div class="panel-body">';
for (var j in data.Categories[i].Products) {
output += '<li><a class="ProdLink" href="https://example.com/api/products/GetProductDetail/'+data.Categories[i].Products[j].product_id+'">'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].coins+' coins</a></li>';
}
output += "</div></div>";
}
output += "</div>";
document.getElementById("accordion").innerHTML = output;
});
</script>
This creates a menu with an item such as this
<a class="ProdLink" href="https://example.com/api/products/GetProductDetail/2">Test Item</a>
To parse the data from this URL I've tried:
<script>
$('#accordion').on('click','a.ProdLink',function(event) {
event.preventDefault();
var url = $(this).attr("href");
$.getJSON(url, function(data) {
var output = '<div>';
for (var i in data) {
output += data[i].full_description;
}
output += "</div>";
document.getElementById("itemdata").innerHTML = output;
});});
</script>
But this isn't working. Any insight would be appreciated.
Upvotes: 2
Views: 88
Reputation: 20636
You are appending links dynamically, so use event delegation to handle events on dynamic elements, here a.ProdLink
.
$('#accordion').on('click','a.ProdLink',function(event){
...
});
Also, this line suggestsProdLink
is the id
, change it to class
t avoid duplicate IDs
output += '<li><a id="ProdLink" ...
And as cloudworks points out the click function should be closed with apt paranthesis.
Upvotes: 2