2016-12-07 28 views
1

HTML:爲什麼JSON.stringify只顯示click事件的isTrusted成員?

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

的Javascript:

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

控制檯結果:

{"isTrusted":true} 

這是發生在Chrome。我還沒有測試過其他瀏覽器。

+0

//jsfiddle.net/sanfords/djf2nxwd - 這是我試圖嵌入原始帖子的小提琴。 –

+2

可能重複的[如何stringify事件對象?](http://stackoverflow.com/questions/11547672/how-to-stringify-event-object) – Mahi

+0

否我採取了回。這是一個騙局。 –

回答

2

有許多的原因,一些屬性沒有得到列入JSON.stringify:

  1. 他們可能是function s,這不能被串化
  2. 他們可能屬於原型(即類)的一個對象,而不是直接屬於該對象本身。

如果您需要包括額外的數據,最好的辦法是手動構建一個新的對象與您要包括的東西:

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

事件本身充滿了樣機的功能 - 這是通過stringify隱藏(正如ForbesLindesay已經指出的那樣)。

否則,在HTML標記中看到onclick並不常見(因爲它會對您的代碼生成非常緊密的依賴關係)。

大多數瀏覽器(超越IE7)也允許控制檯內部拆包值的 - 你可以在這裏看到:http://jsfiddle.net/djf2nxwd/14/

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

這可能是你所期望的行爲。

相關問題