Hướng dẫn create li from array javascript - tạo li từ mảng javascript

Trước hết, đừng tạo các phần tử HTML bằng cách kết hợp chuỗi. Sử dụng thao tác DOM. Nó nhanh hơn, sạch hơn và dễ bị lỗi hơn. Điều này một mình giải quyết một trong những vấn đề của bạn. Sau đó, chỉ cần để nó chấp nhận bất kỳ mảng nào làm đối số:

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]));

Đây là bản demo. Bạn cũng có thể muốn lưu ý rằng set0set1 đang rò rỉ vào phạm vi toàn cầu; Nếu bạn muốn tạo một loại mảng kết hợp, bạn nên sử dụng một đối tượng: 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']
};

Và truy cập chúng như vậy:

makeUL(options.set0);

Cách tạo danh sách HTML ul/li dựa trên nội dung của mảng JavaScript hoặc cách tạo danh sách JavaScript.JavaScript array, or how to create a JavaScript list.

Bằng cách sửa đổi hàm makeList() để chấp nhận các tham số và các thành phần đích, bạn có thể vượt qua các mảng khác nhau và tạo các danh sách khác nhau bên trong các thùng chứa khác nhau.

Giải pháp 1 1

Chức năng JavaScript vani này có các phụ thuộc bằng không và hoạt động trong tất cả các trình duyệt.

function makeList() {
    // Establish the array which acts as a data source for the list
    let listData = [
        'Blue',
        'Red',
        'White',
        'Green',
        'Black',
        'Orange'
    ],

    // Make a container element for the list
    listContainer = document.createElement('div'),

    // Make the list
    listElement = document.createElement('ul'),

    // Set up a loop that goes through the items in listItems one at a time
    numberOfListItems = listData.length,
    listItem,
    i;

    // Add it to the page
    document.getElementsByTagName('body')[0].appendChild(listContainer);
    listContainer.appendChild(listElement);

    for (i = 0; i < numberOfListItems; ++i) {
        // Create an item for each one
        listItem = document.createElement('li');

        // Add the item text
        listItem.innerHTML = listData[i];

        // Add listItem to the listElement
        listElement.appendChild(listItem);
    }
}

// Usage
makeList();

Xem một bản demo jsfiddle & nbsp; ở đây.

Giải pháp 2

Chức năng này nhỏ gọn hơn và sử dụng vòng lặp

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};
0:

let items = [
        'Blue',
        'Red',
        'White',
        'Green',
        'Black',
        'Orange'
    ],
    ul = document.createElement('ul');

document.getElementById('myItemList').appendChild(ul);

items.forEach(item => {
    let li = document.createElement('li');
    ul.appendChild(li);

    li.innerHTML += item;
});

Ở đây, một cách khác để làm điều đó, tương tự như giải pháp đầu tiên.Lưu ý rằng vòng lặp

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};
0 chậm hơn một chút.Xem nó là giải pháp thứ ba dưới đây. Hãy kiểm tra thử nghiệm JSPERF này trong một trình duyệt hiện đại.
Check out this jsPerf test in a modern browser.

Giải pháp 3

const options = [
    set0 = ['Option 1','Option 2'],
    set1 = ['First Option','Second Option','Third Option']
];

function makeUL(array) {
    // Create the list element
    let list = document.createElement('ul');

    for (let i = 0; i < array.length; i++) {
        // Create the list item
        let 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]));

/**
 * Usage
 * Add an element to hold the data:
 * <div id="foo"></div>
 */
makeUL(options.set0);

// or

makeUL(options.set1);

Giải pháp này có thể được mở rộng để chuyển một tham số phần tử đến hàm

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};
2 và hiển thị các mảng khác nhau trong các phần tử khác nhau.

Hướng dẫn create li from array javascript - tạo li từ mảng javascript

Chuyên gia SEO kỹ thuật, lập trình viên JavaScript và nhà phát triển Stack Stack cao cấp.Trên một nhiệm vụ để thử nghiệm với Canvas, Webgl, JavaScript, SEO và WordPress, trong số nhiều thứ khác.Chủ sở hữu của GetButterfly.com, người sáng lập WPDublin và Speedfactor, đồng tổ chức của Dublin WordPress Meetup Group.

Nếu bạn thích bài viết này, hãy tiếp tục và theo dõi tôi trên Twitter hoặc mua cho tôi một ly cà phê để hỗ trợ công việc của tôi!, go ahead and follow me on Twitter or buy me a coffee to support my work!

Bài viết liên quan