javascript - 从不同的父级中删除类
问题描述
如果我单击“ .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");
});
});
解决方案
我<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>
推荐阅读
- vue.js - 环境变量在 Nuxt 应用程序中不可用
- java - For循环不会对数组进行排序以查找多次出现,错误ArrayIndexOutOfBounds
- node.js - 在 json (mongodb) 中存储默认数据的问题
- go - golang切片中的内存泄漏
- blocking - 是否可以在其他人编辑文件时阻止在 DriveFS 中写入文件?
- r - 不能在 R 中的循环 For 中执行 LSD.test
- javascript - 当我们切换到具有相同父类但嵌套在两个不同 div 中的移动视图时,我正在尝试切换到部分
- php - php 中的 mysqli 类偶尔无法加载
- maven - Nexus 存储库中的工件问题
- reactjs - 处理与 react/next api 调用的不一致