Javascript-将Console / DOM输出作为单个JSON输出返回

问题描述 投票:0回答:2

在我的页面中,我添加了一个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">

下面的屏幕快照是我得到的回报:enter image description here

当前输出

{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, …}" }
提前感谢!
javascript json console output onkeyup
2个回答
0
投票
也许是这样?

    // 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">


0
投票
好,首先是第一件事:

您提供给我们的输出示例

在任何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}) } }

这可以通过使对象具有所需的结构来解决您的问题,该结构实际​​上可以根据需要在代码中进一步更新和使用。
© www.soinside.com 2019 - 2024. All rights reserved.