Javascript - вернуть вывод консоли / DOM как один вывод JSON - PullRequest
0 голосов
/ 17 октября 2019

На своей странице я добавил событие onkeyup, чтобы получить клавиши, которые были нажаты в моем input.

Я получаю результаты в моемконсоль, но мне нужно вывести все события как один JSON вывод и return it.

Я новичок в 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, …}

И что мне нужно, так это уметь присваивать эту переменную, например 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, …}"
}

Заранее спасибо!

Ответы [ 2 ]

3 голосов
/ 17 октября 2019

Хорошо, обо всем по порядку:

Пример вывода, который вы нам дали , недопустим в любой спецификации 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 );
    }

}

Пример выходных данных

Это может решить вашу проблему, имея и возражая с желаемой структурой, которую вы действительно можете обновить и использовать по своему усмотрению в своем коде.

1 голос
/ 17 октября 2019

Может быть как то так?

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><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">
...