I got an array that looks like this:
var myArray = {
"ABC.txt": "1",
"AD.txt": "2",
"uploads/": "1",
"uploads/Penguins.jpg": "1",
"uploads/Tulips.jpg": "2",
"morefiles.txt": "2"
};
I'm trying to make a ul li out of it like this:
<ul>
<li>
<a href="ABC.txt" pos="1">ABC.txt</a>
</li>
<li>
<a href="AD.txt" pos="2">AD.txt</a>
</li>
<li rel="folder">
<a href="uploads/" pos="1">uploads</a>
<ul>
<li>
<a href="uploads/Penguins.jpg" pos="1">Penguins.jpg</a>
</li>
<li>
<a href="uploads/Tulips.jpg" pos="2">Tulips.jpg</a>
</li>
</ul>
</li>
<li>
<a href="morefiles.txt" pos="2">morefiles.txt</a>
</li>
</ul>
I'm trying to make it to UL LI using jQuery, and I came up with nothing really just scraps of code nothing even worth putting here.
Please little help.
-
2You may want to have a look at a template engine. One like Mustache.js or any other one would help you.benzonico– benzonico2013年03月10日 17:25:18 +00:00Commented Mar 10, 2013 at 17:25
2 Answers 2
Looks like what you need is some kind of templating engine. Check out ICanHaz, where you can have something like:
<script id="user" type="text/html">
<li>
<p class="name">Hello I'm {{ name }}</p>
<p><a href="http://twitter.com/{{ twitter }}">@{{ twitter }}</a></p>
</li>
</script>
And the initialization script would be as simple as:
var user = ich.user(user_data_object)
Also, this article, Client-Side Templating will explain you something for:
<h1>{{title}}</h1>
<ul>
{{#names}}
<li>{{name}}</li>
{{/names}}
</ul>
Along with this:
var data = {
"title": "Story",
"names": [
{"name": "Tarzan"},
{"name": "Jane"}
]
}
To be converted to this:
<h1>Story</h1>
<ul>
<li>Tarzan</li>
<li>Jane</ul>
</ul>
Comments
Firstly the variable myArray is not an array, an array is defined inside [ ], so it should look something like this
var myArray = [{"ABC.txt" : "1"}, {"AD.txt" : "2"}, {"uploads/" : "1"}, {"uploads/Penguins.jpg" : "1"}, {"uploads/Tulips.jpg" : "2"},{"morefiles.txt" : "2"}];
But to generate the html in your question you are probably better off with the following structure:
var myArray = [
{
"href":"ABC.txt",
"pos" : "1"
},{
"href":"AD.txt",
"pos":"2"
},
...etc
];
Then use another inner array to generate the nested
You can then just iterate through the array using a for loop and append the elements to the as you go