首页 > 解决方案 > 从不同的父级中删除类

问题描述

如果我单击“ .date ”类,我想在“ .date ”类中添加“ .on ”类。并且,从其他 ' .date ' 类中删除 ' .on ' 类。

这是我的代码:

HTML

  <tbody>
                <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td>1</td>
                  <td>2</td>
                  <td class="date">3</td>
                  <td class="date">4</td>
                </tr>
                <tr>
                  <td>12</td>
                  <td class="date">13</td>
                  <td class="date">14</td>
                  <td class="date">15</td>
                  <td class="date">16</td>
                  <td class="date">17</td>
                  <td class="date">18</td>
                </tr>
</tbody>

JavaScript

$(".date").each(function () {
        $(this).click(function () {
          $(this).addClass("on");
          $(this).siblings().removeClass("on");
        });
      });

标签: javascripthtml

解决方案


<table>从您的代码中添加了它,因此它可以正常工作。

根据您的评论,我所做的是.on从具有该类的元素中删除所有类.date,如果您需要更具体,您可以更改该选择器,例如只有某个表您可以将一个类放到表中,然后将选择器修改为".table-class .date"

$(".date").each(function() {
  $(this).click(function() {
    $(".date").removeClass("on");
    $(this).addClass("on");
  });
});
.date {
  width: 20px;
  background-color: red;
  cursor: pointer;
}

.date.on {
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td>1</td>
    <td>2</td>
    <td class="date">3</td>
    <td class="date">4</td>
  </tr>
  <tr>
    <td>12</td>
    <td class="date">13</td>
    <td class="date">14</td>
    <td class="date">15</td>
    <td class="date">16</td>
    <td class="date">17</td>
    <td class="date">18</td>
  </tr>
  <table>


推荐阅读