-2

Here is my code:

<input type=\"text\" id='MsgToSend" + ToClient + "t" + FromClient + "' onkeypress='ClientOnTyping();' />

where the FromClient and the ToClient are dynamically generated.

JavaScript:

function ClientOnTyping() {
  if(e.keyCode==13) {
     // i know i should do this but my problem is what is 'e' in my case how can i specify it ?
  }

}
4

2 回答 2

3

您需要在事件的元素上附加一个事件侦听器keydown

var btn = document.getElementById('MsgToSend');
btn.addEventListerner('keydown', function (e) {
    if(e.keyCode==13) {
     // i know i should do this but my problem is what is 'e' in my case how can i specify it ?
    }
});

在传统浏览器上,您可以通过这种方式附加事件处理程序。

var btn = document.getElementById('MsgToSend');
btn.onkeydown = function (e) {
    e = e || window.event;
    var keyCode = e.keyCode || e.which;
    if(keyCode==13) {
     // i know i should do this but my problem is what is 'e' in my case how can i specify it ?
    }
});
于 2013-03-09T23:23:53.613 回答
0

在处理函数的范围内,e是一个event在 DOM 中触发事件时自动创建的对象。您只需将其传递给您的处理程序。

例如:

<input ...onkeypress="ClientOnTyping(event);">

function ClientOnTyping(e) {
    ...
}

另外,考虑使用不显眼的代码而不是显眼的代码。请参阅突兀和不突兀的 javascript和 Starx 的答案之间的区别。

于 2013-03-09T23:24:18.577 回答