I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data:
{
"india": [
{
"position": "left",
"imgurl":"3.jpg"
},
{
"position": "right",
"imgurl":"2.jpg"
},
{
"position": "left",
"imgurl":"3.jpg"
},
{
"position": "right",
"imgurl":"2.jpg"
}
],
"aus": [
{
"position": "left",
"imgurl":"4.jpg"
},
{
"position": "right",
"imgurl":"2.jpg"
},
{
"position": "left",
"imgurl":"3.jpg"
},
{
"position": "right",
"imgurl":"2.jpg"
}
]
}
Displayed below is the snippet of HTML code containing Javascript functionality:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event) {
$.getJSON('list1.json', function(data) {
$.each(data.india, function (key, val) {
$('.ms-left').append('<div class="ms-section '+val.position+'" id="left3"><img src="'+val.imgurl+'"></div>');
});
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:#cc0;">
STAGE</div>
<ul id="ul"></ul>
<div class="ms-left"></div>
<input type = "button" id = "driver" value = "india" />
<ul id="menu" class="">
<li><a href="" data-value="india">India</a></li>
<li><a href="" data-value="aus">Australia</a></li>
<li><a href="" data-value="usa">USA</a></li>
</ul>
</body>
</html>
The main challenge I face is passing dynamic variables to each function such as $.each(data.india)
. Essentially, I aim to change the parameter from India to AUS, USA dynamically so that the .each
loop can access and retrieve values based on country parameters defined in the JSON data. Assistance is requested for this task.
How can I implement passing a dynamic parameter to the .each
loop in order to efficiently fetch data according to the countries specified in the JSON file? As it stands, the data.india, data.aus references can be manually modified to obtain desired information, but I seek a method to automate this process dynamically.
Above my code lies a structure consisting of list items. My objective entails clicking the link corresponding to India, which will then request JSON data associated with India. Similarly, clicking the AUS link should retrieve relevant data from the JSON source pertaining to Australia.