javascript - 单击复选框后如何在文本中添加一条线?
问题描述
这是我到目前为止得到的,我很肯定问题出在 this.checkBox
var checkBox = document.createElement("input");
checkBox.type = 'checkbox';
if (this.checkBox) {
inputItem.style.textDecoration = "line-through";
} else {inputItem.style.textDecoration = "none";}
解决方案
你将不得不做这样的事情。当复选框发生变化时,通过查看checked
属性来检查复选框是否被选中。如果是这样,请将标签的文本装饰设置为,line-through
否则您可以将其设置为无。
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
这是一个完整的例子:
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
console.log("Delete code!");
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Configure the check box
var checkBox = document.createElement("input");
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input type="submit">
</form>
<ul id="list">
</ul>
</body>
</html>
推荐阅读
- r - 如何在图表上拟合图例
- mongodb - 如何在nifi上设置mongodb的初始偏移量
- json - 获取json响应中的值
- javascript - 我怎样才能隐藏recaptcha溢出-y
- vue.js - Vue:如何使用 axios 将响应数据放入选择选项(vue-search-select)
- c# - 您可以链接到 Razor 组件而不对其 URL 进行硬编码吗?
- rxjs - 当 $foo 发出时,WithLatestFrom($foo) 没有发出,可能是因为使用了合并
- django - .dockerignore:有些文件被忽略,有些没有
- python - 什么是jsl标签
- python - ValueError:使用 matplotlib hexbins 设置具有序列的数组元素