在我的页面中,我添加了一个onkeyup
事件,以获取在我的input
中已经pressed的键。
我在控制台中得到结果,但是我需要将所有events输出为单个JSON
输出,然后将其输出为return
。
我是JS
的新手,感谢您的帮助
PS:由于某些原因,我的代码段在这里不起作用,但是在我的index.html
中,我可以看到事件输出很好。
window.onload = function() {
const myInput = document.getElementById('myInput');
myInput.onkeyup = function(e) {
console.log(e);
}
}
<input type="text" value="" id="myInput">
当前输出:
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
而且我正在寻找的是能够将其[[assign赋给变量,例如var json
,输出将是:]
{
"onkeyup":
"{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "s", code: "KeyS", location: 0, ctrlKey: false, …}
{isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}"
}
提前感谢!
// new Array to store events
let events = []
window.onload = function() {
const myInput = document.getElementById('myInput');
myInput.onkeyup = function(e) {
//console.log(e);
//Push events into array
events.push(e)
// Log events array
console.log({events})
}
}
<input type="text" value="" id="myInput">
您提供给我们的输出示例
在任何JSON规范中均无效,并且在JavaScript中不会作为对象评估(由于引号使用错误)。您想要的是一个具有属性“ onkeyup”(处理的事件的名称)的对象,该对象包含一个对象数组(在您的情况下,该事件的发生)。
// new Array to store events
let events = []
window.onload = function() {
const myInput = document.getElementById('myInput');
myInput.onkeyup = function(e) {
//console.log(e);
//Push events into array
events.push(e)
// Log events array
console.log({events})
}
}
这可以通过使对象具有所需的结构来解决您的问题,该结构实际上可以根据需要在代码中进一步更新和使用。