Javascript - return Console/DOM 输出为单个 JSON 输出

Javascript - return Console/DOM output as a single JSON output

在我的页面中,我添加了一个 onkeyup 事件,以便在我的 input 中获取已被 按下 的键。

我在控制台中得到了结果,但我需要将所有 事件 作为单个 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">

下面的截图是我在return中得到的:

当前输出:

{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, …}

我正在寻找的是能够分配给一个变量,例如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, …}"
}

提前致谢!

也许是这样的?

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre><code>    // 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"(处理的事件的名称)的对象,它包含一个对象数组(在你的例子中,这个事件的发生)。

let obj = { onkeyup: [] };

window.onload = function() {
    const myInput = document.getElementById('myInput');

    myInput.onkeyup = function(e) {
        obj.onkeyup.push(e);
        console.log( obj );
    }

}

Sample output

这可能会解决您的问题,方法是拥有并反对您可以根据需要在代码中进一步更新和使用的所需结构。