gpt4 book ai didi

javascript - 错误: deleteItem function is not defined in my script

转载 作者:行者123 更新时间:2023-12-01 00:27:18 25 4
gpt4 key购买 nike

我在 JavaScript 中编写了一个待办事项列表,但此代码不起作用并显示 deleteItem() 未定义错误。我在codepen中测试了它,它工作正常。

window.onload = function () {
let ourForm = document.getElementById("ourform");
let ourField = document.getElementById("todo");
let ourList = document.getElementById("list");

ourForm.addEventListener("submit", e => {
e.preventDefault();
createItem(ourField.value);
});

function createItem(x) {
let ourHtml = `<li>${x}<button onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", ourHtml);
ourField.value = "";
ourField.focus();
}

function deleteItem(elementToDelete) {
elementToDelete.parentElement.remove();
}

}

<h1>NEED-TO-DO APP</h1>
<form id="ourform">
<input id="todo" type="text" autocomplete="off">
<button>Create Item</button>
</form>
<h3>Need To Do</h3>
<ul id="list">
</ul>

我的脚本有什么问题..

最佳答案

尝试将 deleteItem 函数复制到 window.onload 函数之外,因为目前无法访问作用域。

  window.onload = function () {
let ourForm = document.getElementById("ourform");
let ourField = document.getElementById("todo");
let ourList = document.getElementById("list");

ourForm.addEventListener("submit", e => {
e.preventDefault();
createItem(ourField.value);
});

function createItem(x) {
let ourHtml = `<li>${x}<button onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", ourHtml);
ourField.value = "";
ourField.focus();
}

}
function deleteItem(elementToDelete) {
elementToDelete.parentElement.remove();
}

关于javascript - 错误: deleteItem function is not defined in my script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58872611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com