javascript 使用不显眼的javascript从单个事件调用多个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16428558/
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 04:38:06  来源:igfitidea点击:

call multiple functions from single event with unobtrusive javascript

javascriptjqueryunobtrusive-javascript

提问by dan_vitch

I have an input element

我有一个输入元素

<select id="test"></select>

on change I want to call multiple functions

更改时我想调用多个函数

$('#test').change(function1, function2);

functions for now are just alerts for now

现在的功能只是现在的警报

var function1 = function(){alert('a');};
var function2 = function(){alert('b');};

Only the second function is being called. I know this because of alerts and brake points. I know one way to correct this would be to call function1, and function2 from another function, but I would like to avoid that.

只有第二个函数被调用。我知道这是因为警报和刹车点。我知道纠正这个问题的一种方法是从另一个函数调用 function1 和 function2,但我想避免这种情况。

采纳答案by Drew

I prefer not to use anonymous functions so I would create a new function and place all work inside it.

我不喜欢使用匿名函数,所以我会创建一个新函数并将所有工作放在其中。

$('#test').change(onSelectChange);

var onSelectChange = function() {
    function1();
    function2();
}

回答by Dom

You can always chain them:

您可以随时链接它们:

$('#test').change(function1).change(function2);

回答by Mohammad Adil

You can do this -

你可以这样做 -

$('#test').change(function1);
$('#test').change(function2);

回答by Siamak A.Motlagh

You can do it like this:

你可以这样做:

$('#test').change(function(){function1(); function2();});

回答by Vali D

Why not try something like:

为什么不尝试这样的事情:

$('#test').change(function(){
   function1();
   function2();
};