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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17859644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:53:06  来源:igfitidea点击:

how to call multiple onkeyup events on one html-tag

javascripthtmlasp.net-mvc-4

提问by Daniel Gustafsson

can i call multiple onkeyup events on the same html input-tag?

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

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

something like that?

类似的东西?

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

or like this? ive treid them both but i might have the wrong syntax? or is there a better way to do it?

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

回答by Halcyon

You do not callonkeyupevents, they are events, they happen.

你不onkeyup事件,它们就是事件,它们发生了

You can use the EventListener API to add multiple event listeners.

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

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

The alternative notation would be:

另一种表示法是:

<input .. onkeyup="checkNr(this.id); fill()" type="text">
                                   ^- semicolon

This is similar to:

这类似于:

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

回答by Mx.

Another way to Rome:

去罗马的另一种方式:

If you want to call multiple functions and set the event inline, you could write an extra method that will call all methods.

如果您想调用多个函数并设置内联事件,您可以编写一个额外的方法来调用所有方法。

for ex.

例如。

<input style="float: left; width: 50px;" id="PersonLength" name="PersonLength" onkeyup="yourElemOnKeyup(this.id)" type="text">

Script

脚本

    function yourElemOnKeyup(id){
       checkNr(id);
       fill();
}