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

时间:2010-08-03 15:03:04

标签: 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。任何帮助将不胜感激。谢谢!

5 个答案:

答案 0 :(得分:5)

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

$("#txtValue1, #txtValue2").focus( //etc...

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

$(".txtValue").focus( //etc...

里面模糊功能,你可以参考$(this)而不是回忆选择。

最终结果。

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

答案 1 :(得分:4)

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

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

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

然后你可以使用类jQuery选择器:

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

或者更一般地说,您可以通过以下方式应用于文档中的每个文本框:

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

答案 2 :(得分:0)

为您的元素添加类似textValues的类,然后您可以执行此操作:

$(document).ready(function () {
var currentValue = {};

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

function CallCalculations() {
    // Do Stuff
};

答案 3 :(得分:0)

你可以为这两个输入重构它:

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

答案 4 :(得分:0)

你可以整合类似的东西:

$(document).ready(function() {
  var currentValue = {};

  $("#txtValue1, #txtValue2, #txtValue3, #txtValue4").focus(function() {
    currentValue = $(this).val();
  }).blur(function() {
    $(this).valid();
    if (currentValue != $(this).val() && $(this).val() != "") {
      // DO STUFF??
    }
  });
});

我不知道你是否正在寻找这个?

相关问题