繁体   English   中英

jQuery首先选择表中tr的td,然后遍历结果并将文本与值进行比较

[英]jquery select first td of a tr in a table, then iterate through the findings and compare text with value

有一张桌子,像:

<table id="table_1">
<tr><td>1</td><td>foo</td></tr>
<tr><td>2</td><td>foo</td></tr>
<tr><td>3</td><td>foo</td></tr>
<tr><td>4</td><td>foo</td></tr>
</table>

我想获取每个表行的第一个td。 然后,我想遍历调查结果,并将td中包含的文本值与我拥有的值进行比较。

到目前为止,我可以使用以下命令获取每个tr的第一个td:

var test = $("#table_1").find('td:first-child');

然后我得到tds的数量: console.log(test.length); 但是当我尝试获取td的文本时,出现错误: console.log(test[1].text()); 错误:

Uncaught TypeError: test[1].text is not a function

显然我做错了。 我的思维方式错误吗? 我该如何解决?

test是所有第一个子元素的jquery对象。 您应该使用.eq(0).eq(0) .first()来定位集合中的第一个元素:

 console.log(test.eq(0).text());

要么

 console.log(test.first().text());

更新:要获取数组中第一个孩子的td元素的所有文本

 var allfirsttdtext = test.map(function(){
     return $(this).text();
 }).get();

工作演示

test[1]将返回底层的DOM元素,而.text()是jQuery函数,因此您会遇到错误。

我认为,您需要使用.eq()

将匹配的元素集减少到指定索引处的元素。

test.eq(0).text()

注意:提供的索引是从零开始的,并且是指元素在jQuery对象中而不是在DOM树中的位置。

,使用textContent

test[1].textContent

在JavaScript中使用textContent bcoz您正在将jquery对象转换为javascript对象

console.log(test.eq(0).text());

console.log(test[0].textContent);

您必须用jQuery包围,因为结果数组是Dom Elements:

for(i = 0; i < test.length; i++){
  console.log($(test[i]).text())
}

尝试这个:

var v = 'compare';

 $('#table_1 td').each(function () {
       if ($(this).text() == v)
       console.log($(this).text()+' is equal with the variable '+v);
    })
console.log(test[1].text());

当您说test[1] ->时,test->是htmlDomElement的数组,它为您提供htmlElement而不是该元素的jQuery对象,因此您不能使用.text()这是jQuery函数。

$(test[1]).text()包装它,使其成为jQuery对象以在其上使用text()函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM