简体   繁体   English

Javascript填充字段给出未定义的函数错误

[英]Javascript Populated Fields gives Undefined Function Error

I am creating a todo app. 我正在创建一个待办事项应用程序。 It consists of 3 task to do with status set to false by default. 它由3个任务组成,默认情况下状态设置为false The fields are populated using Javascript. 使用Javascript填充字段。

When the radio button is checked, it should run the completeTask() function. 选中单选按钮后,它应运行completeTask()函数。 But it is giving me the undefined function error. 但这给了我未定义的函数错误。 Please Help! 请帮忙!

 let todoApp = (() => { const container = document.getElementById('todoLister'); const todoList = [ { task: 'Get Up', status: false }, { task: 'Eat stuff', status: false }, { task: 'Goto College', status: false } ]; todoList.forEach((el, id) => { const label = document.createElement('label'); const radio = document.createElement('input'); const br = document.createElement('br'); if(el.status) label.innerText = el.task+'- Done Successfully'; else label.innerText = el.task+'- Not Done'; label.setAttribute('for', el.task); radio.value = id; radio.setAttribute('type', 'radio'); radio.setAttribute('onchange', 'completeTask('+id+')'); container.appendChild(radio); container.appendChild(label); container.appendChild(br); }); let completeTask = (id) => { todoList[id].status = true; if(todoList[id].status) document.getElementsByTagName('label')[id].innerText = 'Done Successfully'; } })(); 
 <div id="todoLister"> </div> 

With your function inside the todoApp , it was not available globally. 由于您的功能位于todoApp ,因此该功能在全球范围内不可用。 You need to move your function and data outside the function so as it is visible globally. 您需要将函数和数据移到函数外部,以便全局可见。

 const todoList = [{ task: 'Get Up', status: false }, { task: 'Eat stuff', status: false }, { task: 'Goto College', status: false } ]; let completeTask = (id) => { todoList[id].status = true; if (todoList[id].status) document.getElementsByTagName('label')[id].innerText = 'Done Successfully'; } let todoApp = (() => { const container = document.getElementById('todoLister'); todoList.forEach((el, id) => { const label = document.createElement('label'); const radio = document.createElement('input'); const br = document.createElement('br'); if (el.status) label.innerText = el.task + '- Done Successfully'; else label.innerText = el.task + '- Not Done'; label.setAttribute('for', el.task); radio.value = id; radio.setAttribute('type', 'radio'); radio.setAttribute('onchange', 'completeTask(' + id + ')'); container.appendChild(radio); container.appendChild(label); container.appendChild(br); }); })(); 
 <div id="todoLister"> </div> 

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

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