首先,不要通过字符串连接创建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);