admin管理员组

文章数量:1302274

HTML:

<button onclick="foo(event);">Test</button>

Javascript:

window.foo = function(event) {
  console.log(JSON.stringify(event));
}

Console Result:

{"isTrusted":true}

It is happening on Chrome. I haven't tested other browsers yet.

HTML:

<button onclick="foo(event);">Test</button>

Javascript:

window.foo = function(event) {
  console.log(JSON.stringify(event));
}

Console Result:

{"isTrusted":true}

It is happening on Chrome. I haven't tested other browsers yet.

Share Improve this question edited Dec 7, 2016 at 14:47 Sanford Staab asked Dec 7, 2016 at 14:40 Sanford StaabSanford Staab 2892 silver badges11 bronze badges 4
  • //jsfiddle/sanfords/djf2nxwd - this is the fiddle I tried to embed in the original post. – Sanford Staab Commented Dec 7, 2016 at 14:42
  • 2 Possible duplicate of How to stringify event object? – Mahi Commented Dec 7, 2016 at 14:46
  • No I take that back. It IS a dupe. – Sanford Staab Commented Dec 7, 2016 at 14:50
  • I dont' think either of the two answers actually answers the question! I have the same issue: when I pass "event" into javascript function from onclick= there are no other properties attached to the event except isTrusted... where are all the other properties (like keyCode)? It really has nothing to do with JSON.stringify ... no other properties seem to exists at all. – jsherk Commented Jun 2, 2020 at 2:59
Add a ment  | 

2 Answers 2

Reset to default 5

There are a number of reasons why some properties do not get included in JSON.stringify:

  1. They might be functions, which cannot be stringified
  2. They might belong to the prototype (i.e. class) of an object, rather than directly belonging to the object itself.

If you need to include extra data, your best bet is to manually construct a fresh object with the things you want to include:

window.foo = function(event) {
  console.log(JSON.stringify({keyCode: event.keyCode));
}

The event itself is full of prototype functions - which are getting hidden by stringify (as ForbesLindesay already pointed out).

Otherwise it's not mon to see onclick in HTML markup (since it generates very tight dependencies with your code).

Most browsers (beyond IE7) also allow you unpacking of values inside the console - which you can see here: http://jsfiddle/djf2nxwd/14/

document.getElementById('foo').onclick = (event) => {
    console.log(JSON.stringify(event));
    console.log(event);
};

That's probably the behaviour you expected.

本文标签: javascriptWhy does JSONstringify only show the isTrusted member of a click eventStack Overflow