如何在每个列表项之前添加复选框,在列表项之后添加删除按钮?

时间:2018-06-16 19:21:58

标签: javascript html checkbox delete-row

我用HTML / Javascript创建了一个待办事项列表。如何在添加到列表中的每个项目的左侧添加一个复选框,并在添加的每个项目的右侧添加一个X按钮以从列表中删除它。这是我到目前为止所得到的



# Data & arithmetic operation  
dfq <- data.frame(ObjVar=c("hat","hat","shoe","shoe","umbrella"),DiscVar=c(0.19,0.39,0.18,1.00,0.64))
dfq$CostVar[dfq$ObjVar == "hat"] <- dfq$DiscVar * 1400
dfq$CostVar[dfq$ObjVar == "shoe"] <- dfq$DiscVar * (1400-342)
dfq$CostVar[dfq$ObjVar == "umbrella"] <- dfq$DiscVar * (1400+500)
&#13;
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");
  listItem.innerText = input.value;
  list.appendChild(listItem);
  inputItem.focus();
  inputItem.select();
  return false;

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

继续使用您以前使用的相同技术,只需继续创建所需的元素并将它们附加到列表项。

&#13;
&#13;
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 check box
  var checkBox = document.createElement("input");
  checkBox.type = 'checkbox';
  
  // Configure the label
  var label = document.createElement("label");
  var labelText = document.createElement("span");
  labelText.innerText = input.value;
  
  // 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;

}
&#13;
<!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>
&#13;
&#13;
&#13;