【问题标题】:Jquery toggling between two classes in a table rowJquery在表行中的两个类之间切换
【发布时间】:2017-10-18 19:29:28
【问题描述】:

我正在使用这个answer 来包含一个在两个 css 类之间切换的开关:twotablecell 和 tablecell,它们是两个不同大小的表格标题单元格,它们在 css 中的大小不同。

单击我的按钮 ID:sizeTog 时,它会将表头类属性更改为 tablecell,但再次单击时不会将其更改回 twotablecell

$('#sizeTog').on('click', function() {
  $('table thead tr .twotablecell').toggleClass("twotablecell tablecell");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th class="twotablecell">
        Name
      </th>
    </tr>
  </thead>
</table>

<input id="sizeTog" type="button" value="toggle size">

我尝试将需要切换的元素更改为:table thead tr th.twotablecell 以使其更具体。

仅当我将 Jquery 切换元素更改为 table thead tr th 时,它才会相应地工作。

但是,我有很多不同的表头列,除了twotablecelltablecell 之外,我希望它们的大小不同。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    问题是因为在第二次单击时,您要查找的元素不再具有 .twotablecell 类 - 第一次单击将其删除。

    通过其他方式选择它,例如使用未删除的不同类:

    $('#sizeTog').on('click', function() {
      $('table thead tr .headercell').toggleClass("twotablecell tablecell");
    });
    .tablecell { color: #C00; }
    .twotablecell { color: #0C0; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <thead>
        <tr>
          <th class="headercell twotablecell">
            Name
          </th>
        </tr>
      </thead>
    </table>
    
    <input id="sizeTog" type="button" value="toggle size">

    【讨论】:

    • 那么他页面中的每一个th都会受到影响?
    • 不,只是.headercell
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2018-05-26
    • 2019-01-11
    相关资源
    最近更新 更多