如何在一个html标记上调用多个onkeyup事件

Dan*_*son 2 html javascript asp.net-mvc-4

我可以在同一个html输入标签上调用多个onkeyup事件吗?

<input style="float: left; width: 50px;" id="PersonLength" name="PersonLength" onkeyup="checkNr(this.id)" onkeyup="fill()" type="text"> 
Run Code Online (Sandbox Code Playgroud)

这样的事情?

<input style="float: left; width: 50px;" id="PersonLength" name="PersonLength"  
onkeyup="checkNr(this.id), fill()" type="text"> 
Run Code Online (Sandbox Code Playgroud)

或者像这样?我喜欢他们两个,但我可能有错误的语法?或者有更好的方法吗?

Hal*_*yon 15

你不会调用 onkeyup事件,它们是事件,它们会发生.

您可以使用EventListener API添加多个事件侦听器.

var input = document.getElementById("my_input");
input.addEventListener("keyup", function () {
    doSomething();
});
input.addEventListener("keyup", function () {
    doSomethingElse();
});
// .. etc
Run Code Online (Sandbox Code Playgroud)

另一种表示法是:

<input .. onkeyup="checkNr(this.id); fill()" type="text">
                                   ^- semicolon
Run Code Online (Sandbox Code Playgroud)

这类似于:

var input = document.getElementById("my_input");
input.addEventListener("keyup", function () {
    checkNr(input.id);
    fill();
});
Run Code Online (Sandbox Code Playgroud)