简体   繁体   English

Javascript - 从对象数组中读取值的复选框

[英]Javascript - checkbox reading value from array of objects

I need to get my checkboxes in todo list read from object in array if task is complete or not.如果任务完成与否,我需要从数组中的 object 读取待办事项列表中的复选框。 And stay checked when they're complete and unchecked or not.并在它们完成和未检查时保持检查。

const todos = [
  {
    id: 1,
    title: 'Nakupit',
    description: 'Mlieko, syr, vajcia',
    completed: false,
  },
  {
    id: 2,
    title: 'Umyt auto',
    description: '+ povysavat',
    completed: true,
  },
]

This is the array and i tried on checkbox something like this.这是数组,我尝试了类似这样的复选框。 And variations, unable to get it work and changing array or value from array making checkbox,checked, if complete和变体,无法使其工作并从数组制作复选框更改数组或值,选中,如果完成

 toDoCheckbox.addEventListener('click', () => {
      if (toDoCheckbox.checked = true) {
       return todos.completed === true
        
      } else {
       return todos.completed === false
      }
    });

Can anyone help with it?任何人都可以帮忙吗?

You can modify the todos state by looking it up by its id and flipping its completed status.您可以通过查找待办事项todosid并翻转其completed状态来修改它。

I added the button to request re-rendering.我添加了请求重新渲染的按钮。 This will re-build the checkboxes using the current state.这将使用当前的 state 重新构建复选框。

 const todos = [{ id: 1, title: 'Nakupit', description: 'Mlieko, syr, vajcia', completed: false, }, { id: 2, title: 'Umyt auto', description: '+ povysavat', completed: true, }] const main = () => { const btn = document.querySelector('.btn-render') btn.addEventListener('click', reRender) renderTodos() } const reRender = (e) => { renderTodos() } const onCheck = (e) => { const id = parseInt(e.currentTarget.dataset.id, 10) const found = todos.find(todo => todo.id === id) if (found) { found.completed =.found.completed // Flip status } } const renderTodos = () => { const container = document.querySelector('.container') container.innerHTML = '' // Clear todos.forEach(todo => { let wrapper = document.createElement('div') let label = document.createElement('label') let checkbox = document.createElement('input') wrapper.classList.add('checkbox-wrapper') label.textContent = todo.title checkbox.type = 'checkbox' checkbox.checked = todo.completed checkbox.dataset.id = todo.id checkbox,addEventListener('change'. onCheck) wrapper.appendChild(label) wrapper.appendChild(checkbox) container.appendChild(wrapper) }) } main()
 .checkbox-wrapper label { display: inline-block; width: 6em; }
 <div class="container"></div> <br /> <button class="btn-render">Re-render</button>

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

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