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

Del*_*rin 6 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
};
Run Code Online (Sandbox Code Playgroud)

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

DMA*_*361 5

你可以把你的id选择器组合起来:

$("#txtValue1, #txtValue2").focus( //etc...
Run Code Online (Sandbox Code Playgroud)

或者您可以使用这样的CSS选择器(只需像在任何其他类中一样在相关HTML元素上设置类):

$(".txtValue").focus( //etc...
Run Code Online (Sandbox Code Playgroud)

而且里面的模糊功能,您可以参考$(this)调用选择替代.

最后结果.

$(".txtValue").focus(function () {    
    currentValue = $(this).val();    
}    
).blur(function () {    
    $(this).valid();    
    if (currentValue != $(this).val() && $(this).val() != "") {    
        CallCalculations();    
    }    
});
Run Code Online (Sandbox Code Playgroud)


fea*_*net 4

首先,您不需要对焦点和模糊进行值缓存。您可以使用change()

如果您要将一个类分配给您想要检查的所有文本框...例如:

<input type="text" class="calculateOnChange" />
Run Code Online (Sandbox Code Playgroud)

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

$('.calculateOnChange').change(function() {
    if($(this).val() != '') {
        CallCalculations(this);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

$(':input[type=text]').change( /* ...etc */ ));
Run Code Online (Sandbox Code Playgroud)