)
I want that my JS create automatic for each JSON Array (name) inside the JSON File > a link with it's name in my HTML File.
For Single Arrays it works fine with the [Number] , but all with the correct name assignment doesn't work (alert throws all yes).
I hope someone knows how?
Thanks Dudes!
Javascript:
// ----- JS ------ //
$.getJSON("json/some.json", function(data) {
$.each([data], function(i, data) {
var data_create_link = "<li><a href='#'><button>1 - "+(Object.keys(data)[0])+"</button></a></li>";
$(data_create_link).appendTo("#div");
});
//alert(Object.keys(data)); /* Alert all Names (work) */
});
JSON:
File: some.json blabla
// ----- JSON ------ //
{
"Queen":[
{
"blabla": "who am i:",
"bla": "who are you :)"
}
],
"Depeche":[
{
"blabla": "is it's me?",
"bla": "grrrrrrr :)"
}
],
"Tiga":[
{
"blabla": "Watttt ?",
"bla": "L ö L"
}
]
}
// -------------------------- End ---------------------------- //
You can use a for in loop.
$.getJSON("json/some.json",function(data){
for(var prop in data){
var data_create_link = "<li><a href='#'><button>1 - "+prop+"</button></a>";
$(data_create_link).appendTo("#div");
}
});
for in iterates over all properties of an object. If you want to read the properties value you could use data[prop]
.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for further reference.
Since you are using jQuery here is the proper jQuery code:
$.each(data, function(key, value){
var link = $('<a></a>')
.prop('href', '#')
.html(key)
;
$('<li></li>')
.html(link)
.appendTo('#div')
;
});
Here is the working example
var data = { 'id': 2, 'number': 3 }; $.each(data, function(key, value) { var link = $('<a></a>') .prop('href', '#') .html(key); $('<li></li>') .html(link) .appendTo('ul'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul></ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.