gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:11:49 24 4
gpt4 key购买 nike

到目前为止,我可以将所有通用文本数据放入数组中,但我在表格单元格内的选择框上遇到了困难。到目前为止,在我的 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 语句,它就会失败,并出现我以前从未见过的错误:

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

我不太确定上面的代码有什么问题,所以如果有人可以提供帮助,我将非常感激。

最佳答案

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

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);
});

关于jquery - 将html表中的所有数据获取到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com