我正在尝试将两个事件侦听器添加到一个杂货列表中,以学习javascript。当我关闭输入时,我想为enter键添加一个on keydown,并为blur添加一个键。问题是,当我尝试添加这两个时,它会出现一个错误,告诉我已经用模糊处理了快捷键,并且不让我同时添加。这是我的代码,建议和帮助非常感谢。
谢谢
et myList = ["bananas", "milk", "apples", "eggs", "cake"];
const btnAdd = document.querySelector("#addNew");
const output = document.querySelector(".output");
const newItem = document.querySelector("#addItem")
btnAdd.addEventListener("click", function () {
console.log("clicked");
if (newItem.value) {
myList.push(newItem.value);
newItem.value = "";
}
build();
})
window.onload = build;
function build() {
output.innerHTML = "<h2>My List</h2>";
const tbl = document.createElement("table");
for (let i = 0; i < myList.length; i++) {
// List
const row = document.createElement("tr");
row.ind = i;
const cell1 = document.createElement("td");
cell1.innerHTML = myList[i];
cell1.classList.add("todo" + i);
row.appendChild(cell1);
// Checkbox
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.classList.add("checkbox" + i);
checkbox.onchange = crossOut;
row.appendChild(checkbox);
function crossOut() {
let completed = document.querySelector(".todo" + i);
if (this.checked) {
completed.style.textDecoration = "line-through";
} else {
completed.style.textDecoration = "none";
}
}
// delete button
const cell2 = document.createElement("td");
const span1 = document.createElement("span");
span1.innerText = "Delete";
span1.addEventListener("click", function () {
//console.log(myList[i]);
//let temp = this.closest("tr").ind;
let itemOut = myList.splice(i, 1);
// This will find what item is at i and remove 1 item
//console.log(myList);
build();
})
cell2.appendChild(span1);
//
const span2 = document.createElement("span");
span2.innerText = "Edit";
span2.addEventListener("click", function () {
row.style.backgroundColor = "Yellow";
let tempEle = row.firstElementChild;
const newInput = document.createElement("input");
newInput.value = tempEle.innerText;
tempEle.innerText = "";
tempEle.appendChild(newInput);
newInput.focus();
newInput.addEventListener("keydown", function (e) {
if (e.keyCode == 13) {
tempEle.innerHTML = newInput.value;
row.style.backgroundColor = "White";
myList[i] = newInput.value;
}
})
// newInput.addEventListener("blur", function (e) {
// tempEle.innerHTML = newInput.value;
// row.style.backgroundColor = "White";
// myList[i] = newInput.value;
// })
// console.log(tempEle);
})
cell2.appendChild(span2);
row.appendChild(cell2)
tbl.appendChild(row);
}
output.appendChild(tbl);
}
发布于 2020-06-25 19:21:21
当您按下键时,您将需要使用keydown事件侦听器,然后您将必须隔离任何键的keyCode。在那之后,你将不得不对keyup做同样的事情,但是使用.mouse0作为密钥码,我很抱歉我不能为你写出来,但我希望这会有帮助。
编辑:如果你查找如何使用keyup,keydown,并查找关键代码是什么,你应该很容易就能解决它。我只使用了jquery,而不是普通的JS。它基本上是以同样的方式完成的
https://stackoverflow.com/questions/62582667
复制相似问题