javascript - Jquery 复选框选中和未选中事件
问题描述
我在 html 中开发了一个代码,其中复选框由 jquery 管理。
<tr>
<td>
<div class="checkbox">
<label><input type="checkbox" id="checkbox2"></label>
</div>
</td>
<td><p id="taks2">Task 2</p></td>
<td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
jquery 脚本是这样的:
<script>
$(document).ready(function(){
$('#checkbox2').click(function(){
if($(this).is(":checked")){
$('#taks2').replaceWith('<s>' + $('#task2').text() + '</s>');
}
else if($(this).is(":not(:checked)")){
}
});
});
</script>
如果用户选中了复选框,则“任务 2”应转换为任务(使用 del 或罢工标签后输出),如果未选中该复选框,则应再次将其转换为以前的形式,如“任务 2”。
解决方案
您可以使用CSS类添加和删除复选框时添加和删除:
$(document).ready(function(){
$('#checkbox2').click(function(){
if($(this).is(":checked")){
$('#taks2').addClass('strike');
} else {
$('#taks2').removeClass('strike');
}
});
});
.strike{
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<div class="checkbox">
<label><input type="checkbox" id="checkbox2"></label>
</div>
</td>
<td><p id="taks2">Task 2</p></td>
<td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
您还可以使用以下方式缩短代码toggleClass()
:
$(document).ready(function(){
$('#checkbox2').click(function(){
var isChecked = $(this).is(":checked");
$('#taks2').toggleClass('strike', isChecked);
});
});
.strike{
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<div class="checkbox">
<label><input type="checkbox" id="checkbox2"></label>
</div>
</td>
<td><p id="taks2">Task 2</p></td>
<td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
推荐阅读
- mysql - MySQL(5.7) 不提示我有关 root db 密码
- python - 添加一个 for 循环作为键,另一个 for 循环作为值
- linux - 如何在 buildspec.yml 中处理输入(是/否)
- android - React Native“Gradle 构建失败并出现异常”
- java - getInputStream() 在设备上非常慢,但在模拟器上没有
- javascript - 三个js解决黑色模型和关闭bump
- javascript - JQuery小册子添加搜索栏
- visual-studio - 代码无法访问 - Visual Studio 中的 React Native
- unity3d - 为什么我的测试视频广告无法在 Android 上运行,但在编辑器上运行?
- python - 按索引名称调用数据框值