【问题标题】:How to extract data into associative array from HTML table using jQuery?如何使用 jQuery 从 HTML 表中提取数据到关联数组中?
【发布时间】:2012-04-25 14:11:12
【问题描述】:
假设我有这样的 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 关联数组吗?该怎么办?
【问题讨论】:
-
Javascript 没有关联数组,只有对象和数字数组(带有数字键的对象)
标签:
javascript
jquery
html
html-table
associative-array
【解决方案1】:
Here's a demo,看控制台。
$(function() {
var words = [];
$('#Words tr').each(function() {
words.push({
cell: $('.cell', this).text(),
desc: $('.desc', this).text()
});
});
console.log(words);
});
【解决方案2】:
鉴于这个特定的用例,那么这将起作用:
var results = {};
$('table#Words tr').each(function(i, x){
results[i] = {
desc: $(x).find('.desc').text(),
cell: $(x).find('.cell').text()
}
});
但是为什么要全部转换成一个对象呢?它的用途是什么,可能有一种更简单的方法来遍历数据。
【解决方案3】:
$('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"})
【解决方案4】:
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);
});
【解决方案5】:
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);
});