【问题标题】:HTML Table nested selectorsHTML 表格嵌套选择器
【发布时间】:2020-06-03 07:36:56
【问题描述】:

我想从 colgroup 中选择某个单元格,但不知道如何。下面是一个例子:

table {
  position:relative;
  top:50px;
  margin:0 auto;
  border-collapse:collapse;
}

td, th {
  border:1px solid black;
  width:75px;
  height:25px;
}

.first {
  background-color:red;
}

.second {
  background-color:yellow;
}

.third {
  background-color:green;
}

.cell {
  background-color:white;
}

.first .cell {
  text-align:left;
  border:5px solid black;
  color:red;
}

.second > .cell {
  text-align:center;
  border:5px solid black;
  color:red;
}

.third .cell {
  text-align:right;
  border:5px solid black;
  color:red;
}
<table>
  <colgroup>
    <col span=2 class='first'>
    <col span=2 class='second'>
    <col span=2 class='third'> 
  </colgroup>
  <thead>
    <th colspan=6>asdad</th>
  </thead>
  <tbody>
    <tr>
      <th>asdad</th>
      <td class='cell'>One</td>
      <th>asdad</th>
      <td>fghfghf</td>
      <th>sdadsad</th>
      <td>yututu</td>
    </tr>
        <tr>
      <th>asdad</th>
      <td>jhkjhk</td>
      <th>asdad</th>
      <td class='cell'>Two</td>
      <th>sdadsad</th>
      <td>yututu</td>
    </tr>
    <tr>
      <th>asdad</th>
      <td>jhkjhk</td>
      <th>asdad</th>
      <td>fghfghf</td>
      <th>sdadsad</th>
      <td class='cell'>Three</td>
    </tr>
  </tbody>
</table>

我已经尝试过大多数here 形式的选择器,但它们似乎不起作用。我怎样才能达到我想要的?我还想使用 Javascript 或 Jquery 选择 #cell 元素。 $('.first #cell') 也不起作用。 $('.first').find('#cell') 也失败了。

【问题讨论】:

  • 元素的id应该不同
  • ID 在 HTML 文档范围内必须是唯一的。
  • “来自一个 colgroup” - 表格单元格可以按 colgroup 元素进行逻辑分组 - 但这并不能使它们成为真正的后代 在 DOM 中。如果您想(在修复 ID 问题后)仅选择某个列组中的单元格 - 那么您必须通过它们在行中的索引或其他方式来执行此操作。
  • 你可以使用class="cell"而不是id='cell',你可以通过类操作符$('.cell')进行选择
  • 首先,ID和NAME不能取一次。

标签: jquery html css css-selectors colgroup


【解决方案1】:

首先,id 在一个页面上只能使用一次。这就是 ids 的概念:独一无二。所以“找到#cell的第一次出现”的想法很奇怪。

如果您有机会为要选择的表格单元格提供 id,事情就很简单了:通过它们的唯一 id 选择它们:

#cell1
#cell2
#cell3
…

在 jQuery 中也是这样:

$('#cell1')
$('#cell2')
$('#cell3')
…

但是,如果您想选择没有 id(或类)的某个单元格,事情可能会变得有点复杂。也许您可以尝试第 n 个子选择器。 https://www.w3schools.com/cssref/sel_nth-child.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2011-03-06
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    相关资源
    最近更新 更多