问题
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