TIA 寻求帮助。当我单击按钮时,我试图创建一个新字段。这是一个待办事项列表项目。我尝试创建一个可以创建新字段的函数。然后,在创建函数后,当单击按钮时,我将其放入 .eventListener 中。我不知道从这里去哪里。
这是我的代码
**Javascript **
const button = document.querySelector('.createnew')
const field = document.querySelector('.field');
function newField() {
const inputElement = document.createElement("input.value");
inputElement.setAttribute("type", "text");
return field.appendChild(inputElement);
}
button.addEventListener('click', newField);
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>To-Do</title>
</head>
<body>
<h1 class="header">To-Do List</h1>
<div class="container">
<div class="form">
<input class="field" type="text" placeholder="Input Text">
<input class="check" type="checkbox">
</div>
<button class="createnew">Add New Field</button>
</div>
<script src="index.js"></script>
</body>
</html>
如果我正确理解你的任务,它可以实现如下所示。
在您的初始代码中,您尝试将新输入作为子项添加到现有输入中,这似乎不正确,因为您需要将新输入添加到表单中。
如果这有帮助,请告诉我。
const button = document.querySelector('.createnew')
const field = document.querySelector('.form');
function newField() {
const inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.setAttribute("class", "field");
inputElement.setAttribute("placeholder", "Input Text");
field.appendChild(inputElement);
const checkboxElement = document.createElement("input");
checkboxElement.setAttribute("type", "checkbox");
checkboxElement.setAttribute("class", "check");
field.appendChild(checkboxElement);
}
button.addEventListener('click', newField);
body {
background-color: rgba(32, 65, 105, 0.656);
}
.header {
display: flex;
flex-direction: column;
align-items: center;
}
.container {
display: flex;
flex-direction: column;
align-items: start;
}
.field {
background-color: rgb(233, 222, 222);
color: rgb(0, 0, 0);
border: none;
width: 700px;
height: 15px;
}
::placeholder {
color: black;
}
.createnew {
display: flex;
flex-direction: column;
align-items: start;
margin: 5px;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>To-Do</title>
</head>
<body>
<h1 class="header">To-Do List</h1>
<div class="container">
<div class="form">
<input class="field" type="text" placeholder="Input Text">
<input class="check" type="checkbox">
</div>
<button class="createnew">Add New Field</button>
</div>
<script src="index.js"></script>
</body>
</html>