簡體   English   中英

如何使用jQuery從HTML表中將數據提取到關聯數組中?

[英]How to extract data into associative array from HTML table using jQuery?

假設我有這樣的HTML,

<table id="Words">
<tr>
    <td class="cell">Hello</td>
    <td class="desc">A word</td>
</tr>
<tr>
    <td class="cell">Bye</td>
    <td class="desc">A word</td>
</tr>
<tr>
    <td class="cell">Tricicle</td>
    <td class="desc">A toy</td>
</tr>

有什么優雅的方法/功能可以將其轉換為Javascript關聯數組嗎? 怎么做呢?

$('tr').map(function(){
    return {
        cell: $('.cell', this).text(),
        desc: $('.desc', this).text()
    }
})

jQuery(Object { cell="Hello", desc="A word"}, Object { cell="Bye", desc="A word"}, Object { cell="Tricicle", desc="A toy"})

http://jsfiddle.net/cyFW5/-在這里,它將適用於具有類的每個td

$(function() {

    var arr = [],
        tmp;

    $('#Words tr').each(function() {

        tmp = {};

        $(this).children().each(function() {

            if ($(this).attr('class')) {
                tmp[$(this).attr('class')] = $(this).text();
            }

        });

        arr.push(tmp);
    });

    console.log(arr);

});​
var table = [];
$('table tr').each(function() {
    var row = [];
    $(this).find('td').each(function() {
        var cell = {};
        cell[$(this).attr('class')] = $(this).html();
        row.push(cell);
    });
    table.push(row);
});

這是一個演示 ,觀看控制台。

$(function() {

    var words = [];

    $('#Words tr').each(function() {
        words.push({
            cell: $('.cell', this).text(),
            desc: $('.desc', this).text()
        });
    });

    console.log(words);

});​

給定此特定用例,則可以使用:

var results = {};
$('table#Words tr').each(function(i, x){
    results[i] = {
      desc: $(x).find('.desc').text(),
      cell: $(x).find('.cell').text()
    }
});

但是,為什么要全部轉換為對象? 它的用途是,可能會有一種更簡單的遍歷數據的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM