如何使用 Jquery 选择第一个 td 元素及其文本
我想在以下 HTML 结构中使用 Jquery 将“Yes! Pick me”更改为“Picked”,我使用了 $('#myDiv>table>tr>td>table>tr').eq(1) .text("Picked");
但它不起作用。有人可以解释一下吗?谢谢!
仅供参考,第一个表本身的第一个 td 包含另一个表...
<div id="myDiv">
<table>
<tr>
<td>
<table>
<tr>
<td>Yes! Pick me!</td>
<td>Not me..</td>
</tr>
<tr>
<td>Not me..</td>
</tr>
</table>
</td>
<td>Not me..</td>
</tr>
<tr>
<td>Not me..</td>
</tr>
</table>
</div>
部分 $('#myDiv>table>tr>td>table>tr>td').eq(1).text(" Picked");
就可以了,我忘了最后一个 td 部分。感谢Rocket和大家的帮助。
I want to change the "Yes! Pick me" into "Picked" with Jquery in the following HTML structure, I used $('#myDiv>table>tr>td>table>tr').eq(1).text("Picked");
But it was not working. Could someone shed some light on this please? Thanks!
FYI, the first td of the the first table itself contains another table...
<div id="myDiv">
<table>
<tr>
<td>
<table>
<tr>
<td>Yes! Pick me!</td>
<td>Not me..</td>
</tr>
<tr>
<td>Not me..</td>
</tr>
</table>
</td>
<td>Not me..</td>
</tr>
<tr>
<td>Not me..</td>
</tr>
</table>
</div>
The section $('#myDiv>table>tr>td>table>tr>td').eq(1).text("Picked");
does the trick, I forgot the last td part. Thanks to Rocket and everyone's help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个:
Try this:
从
#myDiv
元素 ($('#myDiv')
) 开始选择,然后查找一个表内的所有 TD 元素,该表又位于另一个表内 (< code>.find('table table td')),然后仅更改第一个 (.eq(0)
)。文档:
.find()
:http://api.jquery.com/find.eq()
: http://api.jquery.com/eqStart your selection at the
#myDiv
element ($('#myDiv')
), then find all the TD element that are inside a table that is inside another table (.find('table table td')
), then only alter the first one (.eq(0)
).Documentation:
.find()
: http://api.jquery.com/find.eq()
: http://api.jquery.com/eq主要问题是您需要
.eq(0)
而不是.eq(1)
,因为.eq()
是从 0 开始的,并且您没有选择td
,仅选择tr
。除此之外,使用
>
直接后代选择器会使您的选择根本不是很稳健。尝试
$('#myDiv table table td').eq(0).text('Picked');
The main problem is that you want
.eq(0)
not.eq(1)
as.eq()
is 0-based, and you are not selecting thetd
, only thetr
.Other than that using
>
direct descendant selectors makes your selection not very robust at all.Try
$('#myDiv table table td').eq(0).text('Picked');
您可以尝试:
You can try:
您可以使用 :contains(text) 选择器,
但要小心嵌套表格,因为如果您只使用
您将获得后面的单元格及其嵌套的单元格。
You can use the :contains(text) selector
Be careful with nested tables however because if you were to use just
You would get both the cell your after plus the cell it is nested within.
您的子选择器查询将不起作用,因为 HTML5 要求解析器在您的
元素中插入
元素,因为您忘记了放置它们在你自己。也许您应该考虑验证您的 HTML?
Your child selector query won't work because HTML5 requires the parser to insert
<tbody>
elements inside your<table>
elements, since you've forgotten to put them in yourself. Perhaps you should consider validating your HTML?