我有一段代码,当一组表单值更改时,这个人写了三十个函数。

我想将它们合并为一个函数

$('#jobs_held').change(function() {
// do something, with a little variation
});

$('#residence_years').change(function() {
// do something, with a little variation
});

$('#how_long').change(function() {
// do something, with a little variation
});

无论如何,我可以做些类似的事情...
$('#jobs_held', '#residence_years', '#how_long').change(function(){
// do something, with a little variation
});

最佳答案

将它们连接成一个字符串即可使用 multiple-selector

$('#jobs_held,#residence_years,#how_long').change(function(){
    // do something, with a little variation

    // "this" can be used to refer to the specific element
    //     that received the event.

    alert( this.id ); // to alert the ID of the element
});

...或者找到一些共同的身份,例如一个类(class),将其全部选中。

09-25 20:29