Append a List Using Javascript
I'm developing a new project that uses a lot of ul
(unordered list) elements and some of this lists sharing the 开发者_运维知识库same values, so I want to make a Javascript function to automatize the process by passing a array
for the function and returning the HTML for the page. Something like this:
<h1>Test Page</h1>
List fruits:
<script type="text/javascript" charset="utf-8">
var fruits = ["Banana", "Apple", "Pear", "Strawberry", "Lemon"];
do_list(fruits);
</script>
That should generate:
<h1>Test Page</h1>
List fruits:
<ul>
<li>Banana</li>
<li>Apple</li>
<li>Pear</li>
<li>Strawberry</li>
<li>Lemon</li>
</ul>
How to make this?
Given a list of values, and the node you'd like to append, this will create li
tags for every item in that list.
function do_list(arr, ulNode)
{
for(var i = 0; i < arr.length; i++)
{
var node = document.createNode("li");
node.nodeValue = arr[i];
ulNode.appendNodes(node);
}
}
Here's a better version though, it lets you create arbitrary node types -- you can pass in td
as tagName
and a tr
as parentNode
and it would populate that table row.
function do_list(arr, parentNode, tagName)
{
if(!tagName)tagName="li";
for(var i = 0; i < arr.length; i++)
{
var node = document.createNode(tagName);
node.nodeValue = arr[i];
parentNode.appendNodes(node);
}
}
Use example:
<h1>Test Page</h1>
List fruits:
<ul id="list">
<li>Banana</li>
<li>Apple</li>
<li>Pear</li>
<li>Strawberry</li>
<li>Lemon</li>
</ul>
<script type="text/javascript">
do_list(["Banana", "Apple", "Pear", "Strawberry", "Lemon"],
document.getElementById("list"))
</script>
Something like this?
<script type="text/javascript">
function do_list(arr) {
var out = '<ul>';
for (var k=0; k < arr.length; k++) {
out += '<li>' + arr[k] + '</li>';
}
out += '</ul>';
return out;
}
var fruits = ["Banana", "Apple", "Pear", "Strawberry", "Lemon"];
document.write(do_list(fruits));
</script>
Try:
'<ul><li>' + fruitsArray.join('<li>') + '</ul>';
or as a function:
function arrayToList(array) {
return '<ul><li>' + array.join('<li>') + '</ul>';
}
or if you really want closed LI tags (which are optional and not necessary in any browser):
function arrayToList(array) {
return '<ul><li>' + array.join('</li><li>') + '</li></ul>';
}
If you want it inside some element:
function arrayToContainedList(container, array) {
container.innerHTML = '<ul><li>' + array.join('</li><li>') + '</li></ul>';
}
And so on. I think the approach is clear.
精彩评论