创建&LT; UL&GT;并填写基于通过阵列 [英] Create a <ul> and fill it based on a passed array
问题描述
我已经设法以产生基于基质内的一个指定的阵列上的一系列列表项目(即一个阵列内的阵列)。
I've managed to generate a series of list-items based on one specified array within a matrix (i.e. an array within an array).
我希望能够通过一个变量(重presenting数组)的函数,以便它可以吐出充满了基于传递给它的数组列表项的无序列表。
I would like to be able to pass a variable (representing an array) to a function so that it can spit out an unordered list filled with list-items based on the array passed into it.
问题:
- 的功能只有一个阵列工作在一个时间
- 这也产生了标记的逗号(presumably,因为它是数组转换为字符串)
解决方案需要:
- 假定无序列表并不在DOM 存在
- 能够接受传递给它(
选项[0]
,选项[1]
等不同的阵列。) - 生成列表项没有逗号
- assume that the unordered list does not exist in the DOM
- be able to accept different arrays passed into it (
options[0]
,options[1]
, etc.) - generate the list-items without commas
JavaScript的:
var options = [
set0 = ['Option 1','Option 2'],
set1 = ['First Option','Second Option','Third Option']
]
function makeUL(){
var a = '<ul>',
b = '</ul>',
m = [];
// Right now, this loop only works with one
// explicitly specified array (options[0] aka 'set0')
for (i = 0; i < options[0].length; i += 1){
m[i] = '<li>' + options[0][i] + '</li>';
}
document.getElementById('foo').innerHTML = a + m + b;
}
// My goal is to be able to pass a variable
// here to utilize this function with different arrays
makeUL();
jsFiddle
推荐答案
首先,不要创建由字符串连接的HTML元素。使用DOM操作。它的速度更快,更清洁,而且不易出错。仅这一点就可以解决你的问题之一。那么,就让它接受任何数组作为参数:
First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:
var options = [
set0 = ['Option 1','Option 2'],
set1 = ['First Option','Second Option','Third Option']
];
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));
这里有一个演示。 您可能还需要注意的是集0
和 SET1
正在泄漏到全球范围;如果你的意思是创造一种关联数组,你应该使用对象:
Here's a demo. You might also want to note that set0
and set1
are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:
var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};
和访问他们像这样:
makeUL(options.set0);
这篇关于创建&LT; UL&GT;并填写基于通过阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!