javascript-创建一个<ul>并根据传递的数组填充它
我已经设法根据矩阵内的一个指定数组(即数组内的数组)生成一系列列表项。
我希望能够将变量(表示数组)传递给函数,以便它可以根据传递到其中的数组吐出无序列表,其中填充了列表项。
问题:
- 该函数一次只能使用一个数组
- 它还会在标记中产生逗号(大概是因为它将数组转换为字符串)
解决方案需要:
- 假设DOM中不存在无序列表
- 能够接受传递给它的不同数组(
options[0]
、options[1]
等) - 生成没有逗号的列表项
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
gmeben asked 2020-08-12T01:35:53Z
1个解决方案
74 votes
首先,不要通过字符串连接创建HTML元素。 使用DOM操作。 它更快,更干净且不易出错。 仅此一项即可解决您的问题之一。 然后,让它接受任何数组作为参数:
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]));
这是一个演示。 您可能还需要注意,set0
和set1
泄漏到了全局范围内。 如果要创建某种关联数组,则应使用一个对象:
var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};
像这样访问它们:
makeUL(options.set0);