Javascript jquery在表中选择tr的第一个td,然后遍历结果并将文本与值进行比较
有一张像这样的桌子:Javascript jquery在表中选择tr的第一个td,然后遍历结果并将文本与值进行比较,javascript,jquery,html,Javascript,Jquery,Html,有一张像这样的桌子: <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&g
<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>
然后我得到tds的数量:console.log(test.length)代码>
但是当我试图获取td的文本时,我得到了一个错误:console.log(test[1].text())代码>
错误:
显然我做错了什么。我的思维方式错了吗?如何修复它?test
是所有第一个子元素的jquery对象。您应该使用.eq(0)
或.first()
以集合中的第一个元素为目标:
console.log(test.eq(0).text());
或
更新:获取数组中第一个子td元素的所有文本
var allfirsttdtext = test.map(function(){
return $(this).text();
}).get();
测试[1]
将返回底层DOM元素,.text()
是一个jQuery函数,因此您将得到错误
我认为,您需要使用.eq()
将匹配的元素集减少到指定索引处的元素集
代码
注意:提供的索引是从零开始的,它指的是元素在jQuery对象中的位置,而不是在DOM树中的位置
或者,使用
在JavaScript中使用textContent,您正在将jquery对象转换为JavaScript对象
console.log(test.eq(0).text());
或
console.log(测试[0].textContent)代码>由于生成的数组是Dom元素,因此必须用jQuery包围:
for(i = 0; i < test.length; i++){
console.log($(test[i]).text())
}
for(i=0;i
试试这个:
var v = 'compare';
$('#table_1 td').each(function () {
if ($(this).text() == v)
console.log($(this).text()+' is equal with the variable '+v);
})
test->是一个HtmlDomeElement数组
当你说test[1]->
时,它会给你一个HtmleElement而不是该元素的jQuery对象,因此你不能使用.text()
,这是jQuery函数
用$(test[1]).text()将其包装成jQuery对象,以便在其上使用text()
函数。这不是我想要的,因为它返回tds文本的串联。我想分别动态地获取每个值。假设我有10个tds,我希望每个tds的值与一个变量进行比较。如果我有50个tds,我如何分别得到每个值?
test.eq(0).text()
test[1].textContent
console.log(test.eq(0).text());
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());