将html表中的所有数据获取到数组中

时间:2014-11-26 09:28:51

标签: jquery html arrays html-table push

到目前为止,我可以将所有通用文本数据都放到一个数组中,但是我在表格单元格中的选择框中苦苦挣扎。到目前为止,在我的jQuery中我有这个

$('.image-button').click(function(){
        var myTableArray = [];

        $("table#imgList tr").each(function() {
            var arrayOfThisRow = [];
            var tableData = $(this).find('td');
            if (tableData.length > 0) {
                tableData.each(function() {
                    if($(this).has('select').length){
                        arrayOfThisRow.push($(this + ' select option:selected').text());
                    } else {
                        arrayOfThisRow.push($(this).text());
                    } 
                });
                myTableArray.push(arrayOfThisRow);
            }
        });

        console.log(myTableArray);
    });

一旦进入if has select语句就失败了,我之前没见过错误:

  

未捕获错误:语法错误,无法识别的表达式:[object HTMLTableCellElement]

我不确定上述代码有什么问题,所以如果有人能提供帮助,我会非常感激。

2 个答案:

答案 0 :(得分:3)

首先,您不能将字符串附加到对象以创建选择器。您需要使用find()获取当前select中的td

arrayOfThisRow.push($(this).find('select option:selected').text());

其次,您可以使用map()创建数组来缩短代码:

$('.image-button').click(function(){
    var myTableArray = $("table#imgList tr").map(function() {
        var arrayOfThisRow = $(this).find('td').map(function() {
            return $(this).has('select').length ? $(this).find('select option:selected').text() : $(this).text();
        }).get();
        return arrayOfThisRow;
    }).get();
    console.log(myTableArray);
});

答案 1 :(得分:1)

这一行:

arrayOfThisRow.push($(this + ' select option:selected').text());

应更改为:

arrayOfThisRow.push($('select option:selected', this).text());

或:

arrayOfThisRow.push($(this).find('select option:selected').text());