如何将多个jQuery函数压缩成一个?

我仍然是jQuery的新手,我正在尝试寻找帮助优化我的代码方法.我正在开发一个应用程序,每次有人离开字段(.blur)时我都会调用一些计算方法.我只想在满足某些条件时调用这些方法(例如值!= 0).我有9个字段,我正在计算和检查当前.
$(document).ready(function () {
var currentValue = {};

$("#txtValue1").focus(function () {
    currentValue = $(this).val();
}
).blur(function () {
    $("#txtValue1").valid();
    if (currentValue != $("#txtValue1").val() && $("#txtValue1").val() != "") {
        CallCalculations();
    }
});

$("#txtValue2").focus(function () {
    currentValue = $(this).val();
}
).blur(function () {
    $("#txtValue2").valid();
    if (currentValue != $("#txtValue2").val() && $("#txtValue2").val() != "") {
        CallCalculations();
    }
});
});

function CallCalculations() {
    // Do Stuff
};

我知道可以将这些函数压缩成一个更通用的函数(使用CSS类作为选择器而不是ID)但我似乎无法弄明白,因为我仍然是jQuery / Javascript的新手.任何帮助将不胜感激.谢谢!

解决方法

首先,您不需要在焦点和模糊上执行值缓存.您可以使用change().

如果您要将一个类设置为您要检查的所有文本框…例如:

<input type="text" class="calculateOnChange" />

那么你可以使用类jQuery选择器:

$('.calculateOnChange').change(function() {
    if($(this).val() != '') {
        CallCalculations(this);
    }
});

或者更一般地,您可以应用于文档中的每个文本框:

$(':input[type=text]').change( /* ...etc */ ));

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...