【发布时间】:2021-06-10 06:34:37
【问题描述】:
我正在尝试列出待办事项。
当用户在文本框中输入后单击添加时,会在特定表中创建一个新行。
这一行将用户输入作为第一列,在最后一列中,有一个为用户添加的每个输入动态创建的删除按钮。 此按钮必须删除它所在的行才能成功工作。
我已尽我所能找到解决方案,但我在这样做时遇到了麻烦。
感谢任何帮助。
参考代码:
function newTask() {
//retrieves task from input text box
var task = document.getElementById('taskInput').value;
//retrieves everything inside dropdown priority list
var priorityList = document.getElementById('priorityList');
//retrieves the index of selected option in dropdown priority list
var selectedPriorityIndex = priorityList.selectedIndex;
//retrieves text of selected option from dropdown priority list
var selectedPriority = priorityList.options[selectedPriorityIndex].text;
//create a new row
var Row = document.createElement("tr");
//adding task to row
var DataTask = document.createElement("td").appendChild(document.createTextNode(task));
Row.appendChild(DataTask);
//adding priority to row
var DataPriority = document.createElement("td").appendChild(document.createTextNode(selectedPriority));
Row.appendChild(DataPriority);
//adding checkbox to row
var checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkBox");
var DataCheckBox = document.createElement("td").appendChild(checkBox);
Row.appendChild(DataCheckBox);
//add remove button to delete the row
var removeButton = document.createElement("input");
removeButton.setAttribute("type", "button");
removeButton.setAttribute("value", "delete");
//This is the problem. Idk for sure
removeButton.onclick = function name(listRow) {
listRow.remove();
};
var DataDeleteButton = document.createElement("td").appendChild(removeButton);
listRow.appendChild(DataDeleteButton);
//adding entire row to the table
document.getElementById("listTable").appendChild(Row);
}
<!doctype html>
<html>
<head>
<title>
To-Do List Tracker
</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="main">
<form>
<input type="text" class="taskInput" id="taskInput" placeholder="Task">
<select id="priorityList" class="priorityList">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
<input type="button" class="addbtn" value="Add" onclick="newTask()">
</form>
<div class="listheader">
<h2>Task List</h1>
</div>
<table id="listTable">
</table>
</div>
</body>
</html>
【问题讨论】:
标签: javascript onclick dom-events