如何在按下“ Enter”键时调用功能

时间:2019-01-02 21:09:34

标签: javascript for-loop if-statement event-listener enter

这是我的应用程序的JSFiddle链接:https://jsfiddle.net/kdowdell24/a9t7b23c/2/

document.getElementById("add-button").addEventListener("click", function() {

function createNewItem() {
    //creates div element with a class of "input-item"
    let itemContainer = document.createElement("div");
    itemContainer.classList.add("input-item");

    //creates input element and sets type attribute to "checkbox"
    let checkBoxInput = document.createElement("input");
    checkBoxInput.setAttribute("type", "checkbox");
    checkBoxInput.classList.add("check-box");

    //creates input element and sets "type" attribute to "text"
    let textInput = document.createElement("input");
    textInput.setAttribute("type", "text");

    //creates button element and sets "class" to "delete-button" and "type" to "button"
    let deleteButton = document.createElement("button");
    deleteButton.classList.add("delete-button");
    deleteButton.setAttribute("type", "button");

    //creates Font Awesome "X" icon and adds "fas" and "fa-times" classes
    let xIcon = document.createElement("i");
    xIcon.classList.add("fas");
    xIcon.classList.add("fa-times");

    //adds a div to form
    let formElement = document.getElementById("shopping-list");
    formElement.appendChild(itemContainer);

    //adds checkbox, input, and "delete-button" to div
    itemContainer.appendChild(checkBoxInput);
    itemContainer.appendChild(textInput);
    itemContainer.appendChild(deleteButton);

    //adds "X" icon to button
    deleteButton.appendChild(xIcon);

    //removes checkbox, input and deleteButton from form
    deleteButton.addEventListener("click", function() {
        checkBoxInput.remove();
        textInput.remove();
        deleteButton.remove();
        itemContainer.remove();

    });
};

createNewItem();


//Adds new item after pressing Enter key
let itemList = document.querySelectorAll("input[type=text]");
for (var i = 0; i < itemList.length; i++) {
    addEventListener("keypress", function(e) {
        if (e.key === "Enter") {
            createNewItem();
            console.log("New item created!");
        }
    })
}

});

//Removes all content from list after pressing Clear All button
document.getElementById("clear-button").addEventListener("click", function() {
let listContent = document.querySelectorAll(".input-item");
for (var i = 0; i < listContent.length; i++) {
    listContent[i].remove();
}

})

我遇到的问题与这段代码有关:

//Adds new item after pressing Enter key
let itemList = document.querySelectorAll("input[type=text]");
for (var i = 0; i < itemList.length; i++) {
    addEventListener("keypress", function(e) {
        if (e.key === "Enter") {
            createNewItem();
            console.log("New item created!");
        }
    })
}

正在发生的事情是,当我在列表项的文本框中按Enter时,它会添加多个条目,而不仅仅是一个。我要完成的工作是,在按Enter键后,仅在当前条目下方创建一个条目。

2 个答案:

答案 0 :(得分:0)

请谨慎尝试,在任何输入上输入Enter都会触发一个新项,因此请使用标签进行导航

//Adds new item after pressing Enter key
function keyDownListener (e) {
  if (e.keyCode === 13) {
      e.preventDefault();
      createNewItem();
      addListeners()
      console.log("New item created!");
  }
}
function addListeners() {
  let itemList = document.querySelectorAll("input[type=text]");
  for (var i = 0; i < itemList.length; i++) {
    try {
      itemList[i].removeEventListener("keydown", keyDownListener)
    } catch (error) {

    }
    itemList[i].addEventListener("keydown", keyDownListener)
  }
}

此外,人们建议使用.keyCode的{​​{1}}代替13

答案 1 :(得分:0)

如果要在按ENTER键时添加新的复选框,只需更改此内容即可:

let itemList = document.querySelectorAll("input[type=text]");
for (var i = 0; i < itemList.length; i++) {
    addEventListener("keypress", function(e) {
        if (e.key === "Enter") {
            createNewItem();
            console.log("New item created!");
        }
    })
}

对此:

document.addEventListener("keypress", function(e) {
  if (e.key === "Enter" && (document.activeElement.tagName.toLowerCase() !== 'button')) {
    createNewItem();
    console.log("New item created!");
  }
});

我分叉了当前的jsFiddle,并在此处使用了上面的代码:https://jsfiddle.net/AndrewL64/3fcgpxrL/30/

@Moosecouture致谢,他提到使用document.activeElement来防止在按键过程中某个元素处于焦点时不必要的调用。