Get all data in html table into array

喜欢而已 提交于 2019-12-11 03:20:24

问题


So far I can get all generic text data into an array, but I'm struggling with the select boxes within the table cell. So far in my jQuery I have this

$('.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);
    });

It fails once it goes into the if has select statement, with an error I have not seen before:

Uncaught Error: Syntax error, unrecognized expression: [object HTMLTableCellElement]

I'm not really sure what is wrong with the above code so if anyone can help I'd much appreciate that.


回答1:


Firstly, you can't append a string to an object to create the selector. You need to use find() to get the select within the current td:

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

Secondly, you can shorten your code by using map() to create the array:

$('.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);
});



回答2:


This line:

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

should be changed to:

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

or:

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


来源:https://stackoverflow.com/questions/27145490/get-all-data-in-html-table-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!