javascript 将更改事件绑定到 jquery 中的一组输入字段

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

binding on change event to group of input fields in jquery

javascriptjquery

提问by sonam

I have three input fields as below:

我有以下三个输入字段:

 <input type="text" name="address" id="address"/>
 <input type="text" name="city" id="city"/>
 <input type="text" name="country" id="country"/>

How can i add onChange event to all of these fields at once something like this:

如何一次将 onChange 事件添加到所有这些字段,如下所示:

$("select the elements with id address,city,country").bind("change", function() {
            //do something
        });

回答by bipen

use ,in id selector as @Rory said

,如@Rory 所说,在 id 选择器中使用

OR

或者

add a class to all this and call change function

向所有这些添加一个类并调用更改函数

<input type="text" name="address" id="address" class="className"/>
<input type="text" name="city" id="city" class="className"/>
<input type="text" name="country" id="country" class="className"/>

$('.className').bind("change", function(){
  //your stuff
});

HOWEVER

然而

since it is an input field.. i recommend you to use..keyup(), using changeyou have to click out of the text box to make it fire.

因为它是一个输入字段.. 我建议您使用.. keyup(),使用change您必须单击文本框外才能使其触发。

$('.className').keyup(function(){
  //your stuff
});

回答by Rory McCrossan

You can use ,as you would in CSS to combine selectors. Try this:

您可以,像在 CSS 中一样使用来组合选择器。试试这个:

$("#address, #city, #country").bind("change", function() {
    //do something
});

Alternatively you can add a classto each element and select that.

或者,您可以class向每个元素添加一个并选择它。