var keyPress = function(){
x = document.querySelector(".textt");
x.addEventListener("keyup", function(event){
var keyp = document.querySelector(".textt").value;
console.log(event);
document.getElementById("submit").addEventListener("click", function(){
create(event);
x.value = "";
})
})
}
var create = function(event){
var out = document.querySelector(".output");
var displa = document.createElement('li');
displa.textContent = "The key Code for " + event.key + " is: " + event.keyCode;
out.appendChild(displa);
}
function clearAll(){
location.reload();
}

<!DOCTYPE html>
<html>
<head>
<title> ASCI </title>
</head>
<body>
<p> Enter any Character </p>
<form>
<input class="textt" type="text" id = "inp" onkeypress="keyPress()">
</form>
<button id="tt" onclick="clearAll()">Clear</button>
<button id="submit">Submit</button>
<ul class="output">
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
&#13;
**输出1:当我按下一个键时,我第一次能够获得键码 关键的代码是:65 **
**输出2:我第二次按下键我能够获得键码,但它也为我提供了前一键的输出以及按下新键的2倍 关键的代码是:65 关键的代码是:65 b的关键代码是:66 b的关键代码是:66 ** 有人可以帮我解决这个问题吗?我只希望按下新键的输出而不是之前的键。
答案 0 :(得分:0)
使用
x.onkeyup = null;
在x.addEventListener行之前。在分配新的事件监听器之前,它将清除之前的事件监听器。
答案 1 :(得分:0)
前一个答案是正确的,只有使用element.event = function
分配了事件处理程序。对于addEventListener
方法,需要removeEventListener
来处理这些问题。
用法:
element.removeEventListener("the event", the function you want to remove);
但是在你的情况下,你使用匿名函数处理程序。它应该是这样的。
function myFunc(){
console.log("hello world");
}
element.addEventListener("click", myFunc);
element.removeEventListener("click", myFunc);
// This does not work
myFunc = function(){...};
// This also does not work
element.addEventListener("click", function(){console.log("hello world");});
element.removeEventListener("click", function(){console.log("hello world");});