我正在创建一个待办事项列表并尝试创建一个删除按钮。我打算将删除按钮设为一个复选框,但我不确定如何将它添加到我的任务中。
$(() => {
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
var li = $("<li><input type='checkbox' id='newtasklist' class='right-margin' <label>" + newTask + "</label></li>");
$('#tasksUL').append(li);
$(this).val("");
}
}
});
$('body').on('click', ':checkbox', function(e) {
$(this).parent().toggleClass('selected');
});
});
.selected {
text-decoration: line-through;
font-size: 20px;
}
.right-margin {
margin-right: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li><input type="checkbox" id="newtaskitem" class="right-margin"><label>test</label></li>
</ul>
最佳答案
你不能把一个复选框放在一个复选框里,这真的没有意义。浏览器如何知道要采取什么行动。
为了解决您的问题,我添加了一个由 CSS 隐藏的额外复选框,它的标签用于切换复选框。
然后我们使用 jQuery 查找选中删除复选框的元素并删除父级 li
$(() => {
let idx = 0;
$('input').on('keypress', function(e) {
if (e.keyCode == 13) {
const newTask = $(this).val();
if (newTask) {
//Use a template literal, it makes replacing things easier. Use a counter
//to make sure id's are uniqe
idx++;
var li = $(`<li><input type='checkbox' id='newtasklist${idx}' name="done" class='right-margin'><input type='checkbox' id='delete${idx}' name="delete" value="newtaskitem${idx}"><label>${newTask}</label><label class="delete" title="Select item for removal" for='delete${idx}'>♻</label></li>`);
$('#tasksUL').append(li);
}
}
});
$("#deleteItems").on("click", function(){
//find checked delete checkboxes and iterate them
$("#tasksUL [name=delete]:checked").each(function(){
//find the parent list item and remove it
$(this).closest("li").remove();
})
})
});
/*We can do the decoration with CSS*/
#tasksUL input[name=done]:checked~label {
text-decoration: line-through;
font-size: 20px;
}
.right-margin {
margin-right: 30px;
}
/*Hide the delete check box - use the label instead*/
[type="checkbox"][name="delete"] {display:none;}
.delete {margin-left:1em;}
/*Change the appearence when marked for deletion*/
#tasksUL input[name=delete]:checked ~ label {color:#ccc; font-weight:bold}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
<li>
<input type="checkbox" id="newtaskitem0" name="done" class="right-margin">
<input type='checkbox' id='delete${idx}' name="delete" value="newtaskitem0"><label>test</label><label for='delete${idx}' class="delete" title="Select item for removal">♻</label></li>
</ul>
<input type="button" value="Delete marked items" id="deleteItems">
关于javascript - 在复选框内添加复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56963229/