首页 > 解决方案 > 单击复选框后如何在文本中添加一条线?

问题描述

这是我到目前为止得到的,我很肯定问题出在 this.checkBox

    var checkBox = document.createElement("input");
    checkBox.type = 'checkbox';
    if (this.checkBox) {
        inputItem.style.textDecoration = "line-through";
    } else {inputItem.style.textDecoration = "none";}

标签: javascripthtmlcheckboxstyles

解决方案


你将不得不做这样的事情。当复选框发生变化时,通过查看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>


推荐阅读