我开发了一个 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 或 strike 标记后输出),如果复选框未选中,则应再次将其转换为上一个形式类似于“任务 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>
关于javascript - Jquery 复选框选中和未选中事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440703/