为了账号安全,请及时绑定邮箱和手机立即绑定

查找第一个外部标签内的所有标签

查找第一个外部标签内的所有标签

蝴蝶不菲 2022-06-09 10:48:37
你如何在第一个标签中找到所有 tr 标签,id 为 'foo'?<div class="foo">  <tr>...</tr>  <tr>...</tr>  <tr>...</tr></div>我试过了var rows = $("#foo").find('tr');var rows = $("#foo")[0].find('tr'); //trying to only grab the first div or n'th one  for(i in rows) {     console.log(i.innerHTML);  }我的问题是我无法选择第一个 div,然后在该 div 中搜索以找到其中的所有 tr 。
查看完整描述

3 回答

?
www说

TA贡献1775条经验 获得超8个赞

您可以一次全部使用选择器来选择所有元素。考虑以下代码。


$(function() {

  $("#foo tr").each(function(i, el) {

    $(el).attr("id", "row-" + (i + 1));

    console.log($(el).html().trim());

  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="foo">

  <tr>

    <td>Item 1</td>

  </tr>

  <tr>

    <td>Item 2</td>

  </tr>

  <tr>

    <td>Item 3</td>

  </tr>

</table>


使用 CSS 选择器,您可以选择<tr>元素中具有 id 的所有元素foo。


查看完整回答
反对 回复 2022-06-09
?
长风秋雁

TA贡献1757条经验 获得超7个赞

正如其他人指出的那样,<tr>元素不应该是元素的子<div>元素。


也就是说,您只需要按元素类型获取孩子- 即


$(".foo").children("tr");

请注意,您<div>的class“foo”不是id“foo”!


如果您想在 id 上进行选择,那么您的 HTML 应该更像这样。


<table id="foo">

  <tr>...</tr>

  <tr>...</tr>

  <tr>...</tr>

</table>

那么你的选择将是...


$("#foo").children("tr");


查看完整回答
反对 回复 2022-06-09
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

试试这个,如果你要去div:


<div class="foo">

  <tr>...</tr>

  <tr>...</tr>

  <tr>...</tr>

</div>


var rows = $(".foo").find('tr');

$.each( rows , function( i, l ){

  console.log( "Index #" + i + ": " + l );

});

这将为您的 div 下的所有 'tr' 提供类 'foo' 。


但就像其他人说的,先修复html。使用如下table标签:


<table id="foo">

  <tr>...</tr>

  <tr>...</tr>

  <tr>...</tr>

</table>


var rows = $("#foo").find('tr');

$.each( rows , function( i, l ){

  console.log( "Index #" + i + ": " + l );

});


查看完整回答
反对 回复 2022-06-09
  • 3 回答
  • 0 关注
  • 216 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号