在KeyPress

时间:2018-11-03 12:08:39

标签: javascript addeventlistener

由于某种原因,我无法使它工作,在键盘上单击Enter后,新输入会显示不到一毫秒,然后消失

 <!DOCTYPE html>
    <html>
    <head>
        <title>Simple Register Form with JavaScript</title>
    </head>
    <body>
        <form>
            <input type="text" class="regFname" placeholder="First name: ">
            <button>Register</button>
        </form>
        <p>Current Users</p>
        <ul></ul>
    <script type="text/javascript" src="script.js"></script>
    </body>
    </html> 

这是JavaScript

var inputFname = document.querySelector(".regFname");
var button = document.querySelector("button");
var ul = document.querySelector("ul");

function inputLength() {
    return inputFname.value.length;
}
function add() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(inputFname.value));
    ul.appendChild(li);
    inputFname.value = "";
}   
function addUserAfterClick() {
    if (inputLength() > 0) {
        add();
    }
}
function addUserAfterKeyPress(event) {
    if (inputLength() > 0 && event.keyCode === 13) {
        add();
    }
}
button.addEventListener("click", addUserAfterClick);
inputFname.addEventListener("keypress", addUserAfterKeyPress);

1 个答案:

答案 0 :(得分:0)

只需在您的html中添加doc1。如果未指定,则其行为为type="button"

type="submit"
var inputFname = document.querySelector(".regFname");
var button = document.querySelector("button");
var ul = document.querySelector("ul");

function inputLength() {
  return inputFname.value.length;
}

function addUser() {
  if (inputLength() > 0) {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(inputFname.value));
    ul.appendChild(li);
    inputFname.value = "";
  }
}
button.addEventListener("click", addUser);