получить значения из таблицы в виде пары значений ключа с помощью jquery - PullRequest
1 голос
/ 03 июня 2010

У меня есть таблица:

<table class="datatable" id="hosprates">
                <caption> hospitalization rates test</caption> <thead>
                <tr>
                    <th scope="col">Funding Source</th> <th scope="col">Alameda County</th> <th scope="col">California</th>
                </tr>
                </thead>
                <tbody>
                    <tr>
                        <th scope="row">Medi-Cal</th>
                        <td>34.3</td>
                        <td>32.3</td>
                    </tr>
                    <tr>
                        <th scope="row">Private</th>
                        <td>32.2</td>
                        <td>34.2</td>
                    </tr>
                    <tr>
                        <th scope="row">Other</th>
                        <td>22.7</td>
                        <td>21.7</td>
                    </tr>
                </tbody>
            </table>

Я хочу получить значения столбца 1 и столбца 2 для каждой строки в виде пар, которые в конечном итоге будут выглядеть следующим образом: [финансирование, число], [финансирование, число]

Я сделал это до сих пор, но когда я предупреждаю об этом, он показывает только [объект, объект] ...

  var myfunding =  $('#hosprates tbody tr').each(function(){
  var funding = new Object();

  funding.name = $('#hosprates tbody tr td:nth-child(1)').map(function() {
              return $(this).text().match(/\S+/)[0];
             }).get();
  funding.value= $('#hosprates tbody tr td:nth-child(2)').map(function() {
              return $(this).text().match(/\S+/)[0];
             }).get();

});
alert (myfunding);

Ответы [ 2 ]

2 голосов
/ 03 июня 2010
var result = $('#hosprates tbody').children().map(function () {
    var children = $(this).children();

    return {
       name: children.eq(0).text(),
       value: children.eq(1).text()
    };
}).get();

Это создаст массив в виде:

[
 { name : "...", value: "..." },
 { name : "...", value: "..." },
 { name : "...", value: "..." }
]

и т.д.

Чтобы получить имя первого ряда, используйте:

alert(result[0].name);

Для значения:

alert(result[0].value);

Редактировать: если вы хотите получить ТОЧНО, как вы указали:

var result = $('#hosprates tbody').children().map(function () {
    var children = $(this).children();

    return "[" + children.eq(0).text() + "," + children.eq(1).text() + "]"
}).get().join(",");
0 голосов
/ 04 июня 2010

Попробуйте это тогда ( демо ):

var funding = $('#hosprates tbody tr').map(function(){
    return [[ $(this).find('th').eq(0).text() , // find first and only <th>
            $(this).find('td').eq(0).text() ]]; // find first <td> in the row
    }).get();

   alert(funding);  // Output: Medi-Cal,32.3,Private,34.2,Other,21.7

На экране предупреждения отображаются только данные внутри массива, они фактически отформатированы следующим образом:

[["Medi-Cal", "32.3"], ["Private", "34.2"], ["Other", "21.7"]]

Таким образом, вы можете получить данные Medi-Cal следующим образом:

alert(funding[0][0] + ' -> ' + funding[0][1]);  // output: Medi-Cal -> 34.3
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...