2012-10-17 54 views
5

我試圖讓該事件發生::如何將事件對象轉換爲JavaScript中的字符串?

function getEvent(){ 
    alert(window.event); 
} 

我得到事件對象的下方。我想用它來比較字符串。如果事件onclick事件,然後我想要做的行動。我怎樣才能得到它的字符串?或者如何將事件對象轉換爲字符串?

[object MouseEvent] 
+0

爲什麼需要這個?你能給個例子嗎? –

回答

7

使用type屬性。 window.event.type

+0

嘿,謝謝!它的工作。太糟糕了,無法讓你滿意。 – Asmita

+0

+1。當我嘗試在Mozilla瀏覽器中使用alert(window.event.type)時,出現「TypeError:window.event is undefined」,它與Google Chrome配合良好。 – Asmita

+0

這個錯誤非常明顯,window.event沒有定義。 Firefox與chrome處理事件略有不同。你應該改變你的代碼到'function getEvent(e){alert(e.type);}' –

1

使用type屬性讀出類型:

function getEvent(){ 
    alert(window.event.type); 
} 
1

使用event.type特性,例如

<div id="a" onclick="alert(event.type)">Click This</div> 

<div id="b">And This</div>​ 

的Javascript

var func = $('#a').attr('onclick'); 
$('#b').mouseover(function(e) { 
    func(e) 
}); 

DEMOhttp://jsfiddle.net/4tLms/

+0

它不適用於Mozilla Firefox。 – Asmita

+0

我剛剛測試過,工作正常。你有沒有打開javascript? – chridam

相關問題