2015-05-04 65 views
2

我使用下面的代碼從JavaScripte.which沒有工作在IE 9

var whichCode = (window.event) ? e.which : e.keyCode; 

但是得到鍵碼值,它做工精細,除了IE 9,它返回未定義在E 。哪一個。

+0

此代碼在哪裏執行? 請加上完整的代碼。你應該在事件處理程序中使用它! – wallop

+1

而是檢查e.which:'var whichCode = e.which || e.keyCode;'假設e是事件對象。 –

回答

0

此代碼在哪裏執行?請添加完整的代碼。你應該在事件處理程序中使用它! 假設是正確放置試試這個

var keycodeValue = e.which || e.keyCode; 

其中E是事件收到

1

KeyboardEvent.which從未在Internet Explorer中得到實施,被認爲是其他的棄用。

的MDN說明how to most correctly handle keyboard events

window.addEventListener("keydown", function (event) { 
    if (event.defaultPrevented) { 
    return; // Should do nothing if the default action has been cancelled 
    } 

    var handled = false; 
    if (event.key !== undefined) { 
    // Handle the event with KeyboardEvent.key and set handled true. 
    } else if (event.keyIdentifier !== undefined) { 
    // Handle the event with KeyboardEvent.keyIdentifier and set handled true. 
    } else if (event.keyCode !== undefined) { 
    // Handle the event with KeyboardEvent.keyCode and set handled true. 
    } 

    if (handled) { 
    // Suppress "double action" if event handled 
    event.preventDefault(); 
    } 
}, true); 

現在,假設你沒有處理keyDown事件,你也可以使用

var whichCode = e.charCode !== undefined ? e.charCode : e.keyCode; 

注意,這是exactly how it is done in jQuery瀏覽器兼容性:

if (event.which == null) { 
    event.which = original.charCode != null ? original.charCode : original.keyCode; 
} 
+0

對不起,如果這是我的錯誤;這裏沒有嚴格的比較必要嗎?我正在談論'e.which!= undefined'。 '0 == undefined',而'0!== undefined'。 – bardzusny

+0

@bardzusny不,不是必需的:0不是未定義的==。但它更乾淨,這就是我編輯的原因。 –

+0

你說得對,早上好難受我。我在代碼控制檯中輸入了錯誤的代碼。 – bardzusny