How to add value of input text next to checkbox value in list? And how to add onclick property to the input element

huangapple go评论76阅读模式
英文:

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?

&lt;div id=&quot;to-do-list-container&quot;&gt;
 &lt;h3&gt;To do List&lt;/h3&gt;
 &lt;ul id=&quot;list-items&quot;&gt;
  &lt;li&gt;
   &lt;div&gt;
    &lt;input type=&quot;checkbox&quot; class=&quot;list-item-checkbox&quot; onclick=&quot;Check_item()&quot;&gt;Item 1&lt;/input&gt;
   &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
   &lt;div&gt;
    &lt;input type=&quot;checkbox&quot; class=&quot;list-item-checkbox&quot; onclick=&quot;Check_item()&quot;&gt;Item 2&lt;/input&gt;
   &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
   &lt;div&gt;
    &lt;input type=&quot;checkbox&quot; class=&quot;list-item-checkbox&quot; onclick=&quot;Check_item()&quot;&gt;Item 3&lt;/input&gt;
   &lt;/div&gt;
  &lt;/li&gt;
 &lt;/ul&gt;
 &lt;form action=&quot;javascript:void(0);&quot;&gt;
  &lt;input type=&quot;text&quot; id=&quot;list-item-input&quot; placeholder=&quot;Enter item...&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;ADD&quot; onclick=&quot;Add_item()&quot;&gt;
 &lt;/form&gt;
&lt;/div&gt;
function Add_item() {
 var listItem = document.createElement(&quot;li&quot;);
 var container = document.createElement(&quot;div&quot;);
 var checkbox = document.createElement(&quot;input&quot;);
 var itemName = document.getElementById(&quot;list-item-input&quot;);

 itemName.value = &quot;&quot;;

 checkbox.type = &quot;checkbox&quot;;
 checkbox.className = &quot;list-item-checkbox&quot;;

 document.getElementById(&quot;list-items&quot;).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(&quot;li&quot;);
  var container = document.createElement(&quot;div&quot;);
  var checkbox = document.createElement(&quot;input&quot;);
  var itemName = document.getElementById(&quot;list-item-input&quot;).value; // Get the value of the input text

  var label = document.createElement(&quot;label&quot;); // Create a label element for the checkbox text
  label.textContent = itemName; // Set the text content of the label to the input value

  itemName = &quot;&quot;; // Clear the input text after using its value

  checkbox.type = &quot;checkbox&quot;;
  checkbox.className = &quot;list-item-checkbox&quot;;
  checkbox.onclick = Check_item; // Set the onclick property of the checkbox

  document.getElementById(&quot;list-items&quot;).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 = &quot;&quot;;
checkbox.addEventListener(&#39;click&#39;, Check_item);

答案3

得分: 0

关于主要要点,你应该始终在<input>元素中包含一个<label>元素。你可以移除<div>元素,因为它不是必要的,这会使你的标记更加清晰。

此外:

  1. 你应该移除内联JS,而是使用addEventListener来附加事件监听器到使用DOM方法(比如querySelector)选择的元素上。例如,你可以将一个监听器附加到列表元素上,让它捕获来自其子元素的事件(事件委托),因为它们在DOM中“冒泡”。

  2. 而不是使用createElementappend来向列表添加项目元素,你可以使用模板字符串来创建HTML字符串,然后将其添加到列表元素中。

  3. 使用classList,你可以向你在CSS文件中声明的特定元素添加/移除类。

  4. 由于输入元素不需要对应的表单元素,并且在你的示例中没有提交表单,你可以移除它。

<!-- 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 &lt;label&gt; element with &lt;input&gt; elements. You can remove the &lt;div&gt; element as it's not necessary, and it makes your markup a little cleaner.

Further:

  1. You should remove the inline JS and use addEventListener to attach listeners to elements that you pick up with DOM methods like querySelector. 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.

  2. Rather than using createElement and append 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.

  3. Using classList you can add/remove classes to specific elements that you've declared in your CSS file.

  4. 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(&#39;.list&#39;);
const addBtn = document.querySelector(&#39;.form &gt; button&#39;);
// Add a listener to the list element that calls `handleDone`
// and a listener to the button element that calls `handleAdd`
list.addEventListener(&#39;click&#39;, handleDone);
addBtn.addEventListener(&#39;click&#39;, handleAdd);
// When the list element &quot;catches&quot; 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(&#39;[type=&quot;checkbox&quot;]&#39;)) {
const parent = e.target.closest(&#39;li&#39;);
if (e.target.checked) {
parent.classList.add(&#39;strike&#39;);
} else {
parent.classList.remove(&#39;strike&#39;);
}
}
}
// 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 = `
&lt;li&gt;
&lt;label&gt;
&lt;input value=&quot;${value}&quot; type=&quot;checkbox&quot;&gt;
${value}
&lt;/label&gt;
&lt;/li&gt;
`;
list.insertAdjacentHTML(&#39;beforeend&#39;, html);
}

<!-- language: lang-css -->

.strike { text-decoration: line-through; }
.strike label { opacity: 0.7 }; 

<!-- language: lang-html -->

&lt;section&gt;
&lt;h3&gt;To do List&lt;/h3&gt;
&lt;ul class=&quot;list&quot;&gt;
&lt;li&gt;
&lt;label&gt;
&lt;input value=&quot;Item 1&quot; type=&quot;checkbox&quot;&gt;
Item 1
&lt;/label&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;label&gt;
&lt;input value=&quot;Item 2&quot; type=&quot;checkbox&quot;&gt;
Item 2
&lt;/label&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;label&gt;
&lt;input value=&quot;Item 3&quot; type=&quot;checkbox&quot;&gt;
Item 3
&lt;/label&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;section class=&quot;form&quot;&gt;
&lt;input type=&quot;text&quot; placeholder=&quot;Enter item...&quot;&gt;
&lt;button type=&quot;button&quot;&gt;Add item&lt;/button&gt;
&lt;/section&gt;
&lt;/section&gt;

<!-- end snippet -->

Additional documenation

huangapple
  • 本文由 发表于 2023年7月20日 20:54:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定