【问题标题】:How to get specific class element of table?(duplicate class)如何获取表格的特定类元素?(重复类)
【发布时间】:2022-10-04 16:44:08
【问题描述】:

我有 2 个具有相同类元素的表,例如:

<table class="myTbl">
<thead>
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</tbody>
 <table class="myTbl">
<thead>
  <tr>
    <th>C</th>
    <th>D</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</tbody>

当我添加 jquery 函数时 $(function(){ $('.myTbl tbody').function() })

我希望该函数仅在表 1 等特定表中运行,但我有重复的类。怎么做?

而且我不能像更改类或添加 id 那样影响 html 表,... 因为它是从其他导出的,只有 js 或 jquery 才能做到。

我试过$('.myTbl tbody:nth-child(1)') 不工作。

【问题讨论】:

  • 选择第一个表:document.querySelector(".myTbl")document.querySelectorAll(".myTbl")[0]
  • 天哪,太容易了....谢谢!
  • $(".myTbl:first tbody")$(".myTbl:nth-of-type(1) tbody")
  • 还有如何在css中做到这一点?再次感谢。

标签: javascript html jquery


【解决方案1】:

您可以通过在代码中添加 .eq(0) 来做到这一点

$(document).ready(function(){
  $(".myTbl tbody").eq(0).click(function(){
    $(this).hide();
  });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>

<table class="myTbl">
<thead>
  <tr>
    <th>C</th>
    <th>D</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</tbody>
</table>

<hr/>

<table class="myTbl">
<thead>
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</tbody>
</table>

</body>
</html>

【讨论】:

    【解决方案2】:

    那么你应该做

    $(".myTbl:nth-child(2) tbody")
    

    当您的代码选择 .myTbl 然后为此找到第二个 tbody 时,您想要第二次 myTbl。

    或者如果你想要第一个,你应该去

    $(".myTbl:first tbody")
    

    【讨论】:

    • 好吧,那对我不起作用,似乎eq(0) 已经是最好的方法了。
    • 哦,是的,一个不适用于第一个。很好 eq 解决了它,也解决了我的答案。
    【解决方案3】:

    您可以为要选择的元素再添加一个类,也可以按所有选定元素的索引进行选择。

      <!--Consider the following example: -->
    
        <p class="para">Paragraph1</p>
        <p class="para">Paragraph2</p>
        <p class="para">Paragraph3</p>
        <p class="para">Paragraph3</p>
        <script>
        const paragraphs = document.getElementByClassName("para");
        console.log(paragraphs[0]) //outputs the first paragraph
        console.log(paragraphs[1]) //outputs the second paragrah
        console.log(paragraphs[3]) //outputs the third paragraph
            //similarly you can select in jquery too
        </script>
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 2021-01-14
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多