javascript jQuery 多个元素和多个事件的相同功能

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

jQuery same function for multiple elements and multiple events

javascriptjqueryeventstriggers

提问by Toni Peri?

I have a function I'd like to do whenever either user clicks one of the anchor elements, such as this

每当用户单击其中一个锚元素时,我都想做一个功能,例如

$('.element').on('click', function(){
// do stuff here
});

and I want to do the same thing if a select element has changed its value, such as this

如果一个 select 元素改变了它的值,我想做同样的事情,比如这个

$('select').on('change', function(){
// do same stuff here
});

I know I could do

我知道我可以

$('.element', 'select').on('click change', function(){
// do stuff here
});

but that would also trigger whenever I click on the select element and I don't want to confuse user and do something then, just when the select element value has changed.

但这也会在我单击选择元素时触发,并且我不想混淆用户然后在选择元素值更改时执行某些操作。

回答by Kippie

You don't haveto make your function inline.

你不具备让你的函数内联。

var doStuff = function() {
  // do stuff here
});

$('.element').on('click', doStuff);
$('select').on('change', doStuff);

回答by Jacob Mattison

One of the most readable ways to handle this is to create a separate function:

处理此问题的最易读的方法之一是创建一个单独的函数:

function doStuff(){
 //do stuff here
}

$('.element').on('click', function(){
  doStuff();
});

$('select').on('change', function(){
  doStuff();
});

This also gives you a lovely opportunity to make it more clear what your code is for, by giving that function a nice, meaningful name.

这也为您提供了一个很好的机会,通过为该函数提供一个好听的、有意义的名称,让您更清楚地了解您的代码的用途。