英文:
How to add value of input text next to checkbox value in list? And how to add onclick property to the input element
问题
我正在尝试创建一个待办事项列表。我创建了一个JavaScript代码,它将HTML标记附加到列表容器中。但是我如何添加输入复选框旁边的onclick属性和文本值?
<div id="to-do-list-container">
<h3>待办事项列表</h3>
<ul id="list-items">
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">项目1</input>
</div>
</li>
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">项目2</input>
</div>
</li>
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">项目3</input>
</div>
</li>
</ul>
<form action="javascript:void(0);">
<input type="text" id="list-item-input" placeholder="输入项目...">
<input type="submit" value="添加" onclick="Add_item()">
</form>
</div>
function Add_item() {
var listItem = document.createElement("li");
var container = document.createElement("div");
var checkbox = document.createElement("input");
var itemName = document.getElementById("list-item-input");
itemName.value = "";
checkbox.type = "checkbox";
checkbox.className = "list-item-checkbox";
document.getElementById("list-items").appendChild(listItem);
listItem.appendChild(container);
container.appendChild(checkbox);
// 这里需要添加文本值
};
英文:
I'm trying to create a to-do list. I created a JavaScript code that appends the HTML tags in the list container. But how can I add the onclick property and text value of the input text next to the input checkbox?
<div id="to-do-list-container">
<h3>To do List</h3>
<ul id="list-items">
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 1</input>
</div>
</li>
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 2</input>
</div>
</li>
<li>
<div>
<input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 3</input>
</div>
</li>
</ul>
<form action="javascript:void(0);">
<input type="text" id="list-item-input" placeholder="Enter item...">
<input type="submit" value="ADD" onclick="Add_item()">
</form>
</div>
function Add_item() {
var listItem = document.createElement("li");
var container = document.createElement("div");
var checkbox = document.createElement("input");
var itemName = document.getElementById("list-item-input");
itemName.value = "";
checkbox.type = "checkbox";
checkbox.className = "list-item-checkbox";
document.getElementById("list-items").appendChild(listItem);
listItem.appendChild(container);
container.appendChild(checkbox);
checkbox.appendChild(itemName.value);
};
答案1
得分: 1
所以,如果我理解正确,您应该按照以下方式修改代码:
function Add_item() {
var listItem = document.createElement("li");
var container = document.createElement("div");
var checkbox = document.createElement("input");
var itemName = document.getElementById("list-item-input").value; // 获取输入文本的值
var label = document.createElement("label"); // 为复选框文本创建一个标签元素
label.textContent = itemName; // 将标签的文本内容设置为输入值
itemName = ""; // 在使用输入值后清除输入文本
checkbox.type = "checkbox";
checkbox.className = "list-item-checkbox";
checkbox.onclick = Check_item; // 将复选框的onclick属性设置为Check_item()函数
document.getElementById("list-items").appendChild(listItem);
listItem.appendChild(container);
container.appendChild(checkbox);
container.appendChild(label); // 在复选框之后附加标签
};
在这个修改后的Add_item()版本中,创建了一个新的元素来保存输入文本的值,并将其textContent设置为itemName的值。在使用itemName的值后,通过将其设置为空字符串来删除它,以准备下一个元素的输入。
还请注意,我们将复选框的onclick属性分配给Check_item()函数,以确保在单击复选框时执行该函数。
英文:
so, if i understand, you should modify the code as follow:
function Add_item() {
var listItem = document.createElement("li");
var container = document.createElement("div");
var checkbox = document.createElement("input");
var itemName = document.getElementById("list-item-input").value; // Get the value of the input text
var label = document.createElement("label"); // Create a label element for the checkbox text
label.textContent = itemName; // Set the text content of the label to the input value
itemName = ""; // Clear the input text after using its value
checkbox.type = "checkbox";
checkbox.className = "list-item-checkbox";
checkbox.onclick = Check_item; // Set the onclick property of the checkbox
document.getElementById("list-items").appendChild(listItem);
listItem.appendChild(container);
container.appendChild(checkbox);
container.appendChild(label); // Append label after the checkbox
};
In this modified version of Add_item(), a new element is created to hold the input text value and we set its textContent to the value of itemName. After using the itemName value, we delete it by setting it to an empty string to prepare for the next element input.
Note also that we assign the checkbox's onclick property to the Check_item() function, to ensure that the function is executed when the checkbox is clicked.
答案2
得分: 1
你可以使用 Element#append
,它可以插入文本节点。此外,只有在将字符串添加到容器后,你才应该将 itemName.value
设置为空字符串。
可以使用 addEventListener
来添加点击监听器。
container.append(checkbox, itemName.value);
itemName.value = "";
checkbox.addEventListener('click', Check_item);
英文:
You can use Element#append
, which can insert text nodes. Moreover, you should set itemName.value
to an empty string only after adding the string to the container.
addEventListener
can be used to add the click listener.
container.append(checkbox, itemName.value);
itemName.value = "";
checkbox.addEventListener('click', Check_item);
答案3
得分: 0
关于主要要点,你应该始终在<input>
元素中包含一个<label>
元素。你可以移除<div>
元素,因为它不是必要的,这会使你的标记更加清晰。
此外:
-
你应该移除内联JS,而是使用
addEventListener
来附加事件监听器到使用DOM方法(比如querySelector
)选择的元素上。例如,你可以将一个监听器附加到列表元素上,让它捕获来自其子元素的事件(事件委托),因为它们在DOM中“冒泡”。 -
而不是使用
createElement
和append
来向列表添加项目元素,你可以使用模板字符串来创建HTML字符串,然后将其添加到列表元素中。 -
使用
classList
,你可以向你在CSS文件中声明的特定元素添加/移除类。 -
由于输入元素不需要对应的表单元素,并且在你的示例中没有提交表单,你可以移除它。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// 获取列表元素和按钮元素
const list = document.querySelector('.list');
const addBtn = document.querySelector('.form > button');
// 向列表元素添加调用`handleDone`的监听器,
// 并向按钮元素添加调用`handleAdd`的监听器
list.addEventListener('click', handleDone);
addBtn.addEventListener('click', handleAdd);
// 当列表元素“捕获”其子元素的事件时,首先检查它是否是复选框。
// 如果是,它将获取最近的列表元素(即父元素),
// 然后根据情况添加/移除strike类。
function handleDone(e) {
if (e.target.matches('[type="checkbox"]')) {
const parent = e.target.closest('li');
if (e.target.checked) {
parent.classList.add('strike');
} else {
parent.classList.remove('strike');
}
}
}
// 当按钮被点击时,它将获取输入元素的值(即其previousElementSibling),
// 然后使用模板字符串构建一些HTML,将该HTML添加到列表元素中使用`insertAdjacentHTML`
function handleAdd() {
const { value } = this.previousElementSibling;
const html = `
<li>
<label>
<input value="${value}" type="checkbox">
${value}
</label>
</li>
`;
list.insertAdjacentHTML('beforeend', html);
}
<!-- language: lang-css -->
.strike { text-decoration: line-through; }
.strike label { opacity: 0.7 };
<!-- language: lang-html -->
<section>
<h3>待办事项列表</h3>
<ul class="list">
<li>
<label>
<input value="任务1" type="checkbox">
任务1
</label>
</li>
<li>
<label>
<input value="任务2" type="checkbox">
任务2
</label>
</li>
<li>
<label>
<input value="任务3" type="checkbox">
任务3
</label>
</li>
</ul>
<section class="form">
<input type="text" placeholder="输入项目...">
<button type="button">添加项目</button>
</section>
</section>
<!-- end snippet -->
附加文档
英文:
With regard to the main point you should always be including a <label>
element with <input>
elements. You can remove the <div>
element as it's not necessary, and it makes your markup a little cleaner.
Further:
-
You should remove the inline JS and use
addEventListener
to attach listeners to elements that you pick up with DOM methods likequerySelector
. For example you can attach one listener to the list element and have that catch events from its children (event delegation) as they "bubble up" the DOM. -
Rather than using
createElement
andappend
to add item elements to the list you can use a template string to create a string of HTML which you can then add to the list element. -
Using
classList
you can add/remove classes to specific elements that you've declared in your CSS file. -
Since input elements don't require a corresponding form element, and you're not submitting the form in your example, you can remove it.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// Grab the list element, and the button element
const list = document.querySelector('.list');
const addBtn = document.querySelector('.form > button');
// Add a listener to the list element that calls `handleDone`
// and a listener to the button element that calls `handleAdd`
list.addEventListener('click', handleDone);
addBtn.addEventListener('click', handleAdd);
// When the list element "catches" an event from one of its
// child elements it first checks to see if its a checkbox.
// If it is it grabs the closest list element (ie the parent),
// and then either adds/removes the strike class from it
function handleDone(e) {
if (e.target.matches('[type="checkbox"]')) {
const parent = e.target.closest('li');
if (e.target.checked) {
parent.classList.add('strike');
} else {
parent.classList.remove('strike');
}
}
}
// When the button is clicked it grabs the value from
// the input element (its previousElementSibling), and then
// constructs some HTML using a template string using the value
// It then adds that HTML to the list element using `insertAdjacentHTML`
function handleAdd() {
const { value } = this.previousElementSibling;
const html = `
<li>
<label>
<input value="${value}" type="checkbox">
${value}
</label>
</li>
`;
list.insertAdjacentHTML('beforeend', html);
}
<!-- language: lang-css -->
.strike { text-decoration: line-through; }
.strike label { opacity: 0.7 };
<!-- language: lang-html -->
<section>
<h3>To do List</h3>
<ul class="list">
<li>
<label>
<input value="Item 1" type="checkbox">
Item 1
</label>
</li>
<li>
<label>
<input value="Item 2" type="checkbox">
Item 2
</label>
</li>
<li>
<label>
<input value="Item 3" type="checkbox">
Item 3
</label>
</li>
</ul>
<section class="form">
<input type="text" placeholder="Enter item...">
<button type="button">Add item</button>
</section>
</section>
<!-- end snippet -->
Additional documenation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论