开发者问题收集

如何使用附加到文档的侦听器将事件传递给 JavaScript 中的函数调用?[重复]

2017-05-08
1066

我尝试使用以下代码在简单的网页上观察按键:

document.addEventListener("onkeypress", currentKeyPress(event));
function currentKeyPress(event){
    var keynum;
    console.log(event.which);
    if(document.event){
        keynum = event.keyCode;
    } else if(event.which){
        keynum = event.which;
        console.log(event.which);
    }
    document.getElementById("info").innerHTML = keynum;

当我这样做时,我在 Firefox 中收到“ReferenceError:事件未定义”。我需要做什么来解决这个问题?

3个回答
document.addEventListener("keypress", currentKeyPress);
function currentKeyPress(event){
    var keynum;
    console.log(event.which);
    if(document.event){
        keynum = event.keyCode;
    } else if(event.which){
        keynum = event.which;
        console.log(event.which);
    }
    //document.getElementById("info").innerHTML = keynum;
    console.log(keynum)
}
<input>
prasanth
2017-05-08

您不需要传递事件变量:

请按如下方式操作:

document.addEventListener("onkeypress", currentKeyPress);
function currentKeyPress(event){
    var keynum;
    console.log(event.which);
    if(document.event){
        keynum = event.keyCode;
    } else if(event.which){
        keynum = event.which;
        console.log(event.which);
    }
    document.getElementById("info").innerHTML = keynum;
}

事件会自动传递到 currentKeyPress 函数。

请参阅以下示例:

document.getElementById('paraxxx').addEventListener("click", doThis);
function doThis(event){
    console.log(event)
}
<p id="paraxxx">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>

此处,当您单击该段落时,您将调用 doThis 函数,并且事件将传递给该函数。

Shakti Phartiyal
2017-05-08
document.addEventListener("onkeypress", currentKeyPress(event)); //error 

解析器期望 document.addEventListener 的第二个参数是一个函数,现在您要传递函数调用的结果以及当前范围内未定义的事件变量(因此出现异常),您只需传递对该函数的引用。事件触发后,Javascript 会立即回调您的函数,并将事件作为参数提供

将其更改为:

document.addEventListener("keypress", currentKeyPress));
Karim
2017-05-08