【问题标题】:How do I add a class with jQuery to a separate DIV only when a table ROW has a certain class?仅当表 ROW 具有特定类时,如何将带有 jQ​​uery 的类添加到单独的 DIV?
【发布时间】:2018-12-19 17:12:16
【问题描述】:

我正在尝试将 open 类添加到表外的另一个 DIV,仅当表行具有 selected 类时。

<table id="#resultsTable">
  <tbody>
    <tr class="selected">
      <td>Follow the white rabbit...</td>
    </tr>
</table>

<div class="profile open"></div>

这行不通……

$(document).ready(function () {
if ($("#resultsTable tbody tr").hasClass("selected")) {
    $(".profile").addClass("open");
}});

也不是这个……

$('table tbody tr.selected').closest('.profile').addClass('open');

我做错了什么? TIA

【问题讨论】:

  • id="#resultsTable" 不正确。使用id="resultsTable"。 html 属性也不应该是驼峰式,而是除以-。所以results-table 会更好。在 javaScript 中声明变量时应该使用 camelCase,例如。

标签: jquery datatables css-selectors


【解决方案1】:

HTML 中的id 值应该是resultsTable 而不是#resultsTable

$(document).ready(function() {
  if ($("#resultsTable tbody tr").hasClass("selected")) {
    $(".profile").addClass("open");
  }
});
.open{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="resultsTable">
  <tbody>
    <tr class="selected">
      <td>Follow the white rabbit...</td>
    </tr>
</table>

<div class="profile">div content</div>

【讨论】:

    【解决方案2】:

    您的第一个解决方案不起作用,因为 &lt;table id="#resultsTable"&gt; 应该是 &lt;table id="resultsTable"&gt;。注意表的id 属性中的#

    您的第二个解决方案不起作用,因为 closest() 搜索从元素本身到它在 DOM 树中的祖先。但是tr.selected 没有类profile 的任何祖先。

    【讨论】:

    • 感谢伊利什的回复!有没有可以找到 tr.selected 的 JS 选择器?
    猜你喜欢
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2011-06-05
    • 2021-01-16
    相关资源
    最近更新 更多