简体   繁体   English

如何制作每个 <li> 有一个复选框(HTML和Javascript)

[英]How to make each <li> have a checkbox (HTML & Javascript)

I'm creating a Chrome Extension that allows the user to create a todo list. 我正在创建一个Chrome扩展程序,该扩展程序允许用户创建待办事项列表。 So far I am able to type in a task and submit it. 到目前为止,我已经可以输入任务并提交。 Now I want this input, which is a list, to have a checkbox. 现在,我希望此输入(它是一个列表)具有一个复选框。 Right now, whenever the user submits a task, it is counted as a list. 现在,每当用户提交任务时,该任务便被视为一个列表。

HTML: HTML:

<input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask">
<ul id="tasksUL">
  <li><input type="checkbox"><label>test</label></li>
</ul>

Javascript: Javascript:

$(() => {
   $('input').on('keypress', function(e) {
     if (e.keyCode == 13) {
       const newTask = $(this).val();
       if (newTask) {
         const li = document.createElement('li');
         li.textContent = newTask;
         $('#tasksUL').append(li);
         $(this).val("");
       }
     }
   });
 });

add child to li,just like above you done. 把孩子加到li上,就像上面所做的一样。

const input=document.createElement('input')
         input.type="checkbox"
         li.append(input)

Well, by the way you're doing, you'll first have to create the input checkbox and its label and then add it to the list. 好吧,按照您的操作方式,首先必须创建输入复选框及其标签,然后将其添加到列表中。

Here is an example with your code: https://codepen.io/pedrovsn/pen/ZdqrGw 这是您的代码的示例: https : //codepen.io/pedrovsn/pen/ZdqrGw

$(() => {
   $('input').on('keypress', function(e) {
     if (e.keyCode == 13) {
       const newTask = $(this).val();
       if (newTask) {
          const label = document.createElement('label')
          label.innerText = newTask;

            const checkbox = document.createElement('input');
          checkbox.name = 'checkbox';
          checkbox.type = 'checkbox';
          checkbox.value = newTask;

                    const li = document.createElement('li');
          li.appendChild(checkbox);
          li.appendChild(label);
                    $('#tasksUL').append(li);
          $(this).val("");
       }
     }
   });
 });

try this... 尝试这个...

 $(() => { $('input').on('keypress', function(e) { if (e.keyCode == 13) { const newTask = $(this).val(); if (newTask) { var li = $("<li><input type='checkbox'<label>" + newTask + "</label></li>"); $('#tasksUL').append(li); $(this).val(""); } } }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <input type="text" name="newtask" value="" spellcheck="false" placeholder="New Task" id="newtask"> <ul id="tasksUL"> <li><input type="checkbox"><label>test</label></li> </ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM