Я новичок в javascript и написал простую программу, в которой по щелчку мыши и нажатию клавиши ввода значение поля ввода будет напечатано в упорядоченном списке.Я могу напечатать значение, используя событие нажатия кнопки, но не могу напечатать его с помощью нажатия клавиши (клавиша ввода).
Это ошибка, которую я получаю:
[Нарушение] Обработчик нажатия клавиши занял 886ms
JavaScript:
let button=document.getElementById("enter");
let input=document.getElementById("ip");
let ol=document.getElementById("oList")
//variable button binds addEventListener method to a click event
//listening to click event and performning action onclick
button.addEventListener("click",function() {
//if input's length is greater than 0 then create li, append the input to li and then append li with orderd list else will print nothing to add
if(input.value.length>0) {
//created a list tag to add results after user submits
console.log(input.value);
let li=document.createElement("li");
//will append the newly create li with same text "testing"
//createTextNode creates text
li.appendChild(document.createTextNode(input.value));
//the text will be added to the ordered list
ol.appendChild(li);
//reason for input.value=""; is that it will reset the input field after submitting the value
//if this is not given then input field won't be resetted everytime on input submit
input.value="";
}
else {
alert("nothing to add")
}
})
input.addEventListener("keypress", function(event) {
if(input.value.length>0 && event.keycode==13) {
let li=document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ol.appendChild(li);
input.value="";
}
else {
alert("nothing to enter");
}
})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Shopping list</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="list" id="1">
<h1 id="2" >Shopping List</h1>
<h2 id="3">Items:</h2>
<input type="text" id="ip">
<button type="button" class="btn btn-primary" id="enter">Add</button>
<ol id="oList">
<li>a</li>
</ol>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="shoppingList.js"></script>
</body>
</html>