简体   繁体   中英

The changes occurs briefly using keydown and then disappear

I want to append an li when the enter key is pressed using keydown. However, when I press the enter key the new li appears momentarily and then disappear. How can I make it save the change or how can I fix the code?

var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");

enterTodo.addEventListener('keydown', (event)=>{
    if(event.which == 13){
        var todo = enterTodo.value;
        todoList.append("<li>" + todo + "</li>");
    };
})

The reason why it was showing up and dissapearing almost immediately is because forms automatically refresh the page on submit. Which is why you have to use preventDefault in the onSubmit event.

I set up two working samples based on your code. In both, I went ahead and got your code to to append the proper li elements rather than the text `<li>${todo}</li>` to the todoList. I also made the enterTodo clear after being added to the list.

  1. This uses the code about how you had it with the event listener on keydown, but it prevents the refresh.

 var submitBtn = document.querySelector("input[type = 'submit'"); var enterTodo = document.querySelector("input[type = 'text']"); var todoList = document.querySelector("#todoList"); var form = document.querySelector("form"); form.onsubmit = (evt) => evt.preventDefault(); function addTodo() { var todo = enterTodo.value; var li = document.createElement('li'); li.textContent = todo; todoList.appendChild(li); enterTodo.value = ""; } enterTodo.addEventListener('keydown', (event) => { if (event.which == 13) { addTodo(); }; })
 <body> <form> <input type="text" onsubmit="" /> <input type="submit" /> <ul id="todoList"></ul> </form> </body>

  1. This uses the from's onSubmit handler to perform the addition to the todoList instead of directly handling the enter key in the text input. This has the added benefit of also supporting the submit button click as well.

 var submitBtn = document.querySelector("input[type = 'submit'"); var enterTodo = document.querySelector("input[type = 'text']"); var todoList = document.querySelector("#todoList"); var form = document.querySelector("form"); function addTodo() { var todo = enterTodo.value; var li = document.createElement('li'); li.textContent = todo; todoList.appendChild(li); enterTodo.value=''; } form.onsubmit = (evt) => {evt.preventDefault(); addTodo(); }
 <body> <form> <input type="text" onsubmit="" /> <input type="submit" /> <ul id="todoList"></ul> </form> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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