获取html表格中的所有数据到数组中 [英] Get all data in html table into array
问题描述
$('。image-button')。click(function(){
var myTableArray = [];
$(table#imgList tr)。 (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有select语句,它就会失败,并有一个我以前没有看到的错误:
$ b
未捕获错误:语法错误,无法识别的表达式:[object HTMLTableCellElement]
我不确定上面的代码有什么问题,所以如果有人可以帮忙的话,我会非常感激。
首先,您不能将字符串附加到对象来创建选择器。您需要使用 find()
来获取当前 td $内的
select ($(this).find('select option:selected')。text(c code):
arrayOfThisRow.push ));
其次,您可以使用 map()$来缩短代码c $ c>创建数组:
$('。image-button')。click(function(){
var myTableArray = $(table#imgList tr)。map(function(){
var arrayOfThisRow = $(this).find('td')。 b返回$(this).has('select')。length?$(this).find('select option:selected')。text():$(this).text();
}) .get();
return arrayOfThisRow;
})。get();
console.log(myTableArray);
});
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.
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);
});
这篇关于获取html表格中的所有数据到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!