创建一个 <ul>并根据传递的数组填充它 [英] Create a <ul> and fill it based on a passed array

查看:21
本文介绍了创建一个 <ul>并根据传递的数组填充它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法根据矩阵中的一个指定数组(即数组中的数组)生成了一系列列表项.

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).

我希望能够将一个变量(代表一个数组)传递给一个函数,以便它可以根据传入的数组吐出一个填充有列表项的无序列表.

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.

问题:

  • 该函数一次只能处理一个数组
  • 它还在标记中生成逗号(大概是因为它将数组转换为字符串)

解决方案需要:

  • 假设 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

推荐答案

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

这是一个演示.您可能还想注意set0set1 正在泄漏到全局范围内;如果你想创建一种关联数组,你应该使用一个对象:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆