多个元素的事件监听器-jQuery [英] Event listener for multiple elements - jQuery

查看:697
本文介绍了多个元素的事件监听器-jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前正在使用的ASP MVC页面中,三个输入字段的值确定了第四个的值.邮政编码,州代码和其他称为香奈儿代码"的值将确定第四个字段(称为区域代码")的值.

In the ASP MVC page I'm currently working on, the values of three input fields determine the value of a fourth. Zip code, state code, and something else called a Chanel Code will determine what the value of the fourth field, called the Territory Code, will be.

我几周前才开始学习jQuery,所以我首先认为您可以放置​​一个.change事件,该事件检查其他两个字段中的值,如果存在,则调用一个单独的方法来比较这三个和确定地区代码.但是,我想知道是否有一种更优雅的方法来处理此问题,因为似乎在不同的地方编写了很多相同的代码.

I just started learning jQuery a couple weeks ago, so I would first think you could put a .change event that checks for values in the other two fields and, if they exists, call a separate method that compares the three and determines the Territory code. However, I'm wondering if there is a more elegant way to approach this since it seems like writing a lot of the same code in different places.

推荐答案

您可以通过指定多个选择器将回调绑定到多个元素:

You can bind a callback to multiple elements by specifying multiple selectors:

$(".field1, .field2, .field3").click(function() {
    return field1 +
           field2 + 
           field3;
});

如果您需要根据单击的元素来执行特定的操作,另一种选择是创建一个函数来执行实际的计算,然后从每个回调中调用该函数.

If you need to perform specific actions depending on which element was clicked, another option would be to create a function which performs the actual computation and then invoke that from each callback.

var calculate = function() {
    return field1 +
           field2 + 
           field3;
};

然后在每次单击时调用此函数:

And then invoke this function when on each click:

$(".field1").click(function() {
    // Perform field1-specific logic
    calculate();
});

$(".field2").click(function() {
    // Perform field2-specific logic
    calculate();
});

// etc..

这意味着您不会重复自己.

This means that you do not repeat yourself.

这篇关于多个元素的事件监听器-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆