2011-05-12 79 views
0

我已经得到了一系列代码,这些代码将用于联系表单中的大多数输入项目;为了代码行,我希望将这个功能作为一个函数来运行。这里是块的例子:如何将重复的代码块转换为函数

$('#country_code').blur(function() { 
var countryCode = $('#country_code').val(); 
    if(validateNumber(countryCode) == true) { 
     if(countryCode.lastIndexOf('+') != 0) { 
      countryCode = countryCode.replace('+', ''); 
      $('#country_code').val('+' + countryCode); 
     } 
    } 
    else { 
     countryCode = ''; 
     $('#country_code').val(countryCode); 
    } 
}); 

我想创建像函数如下:

function validateElements(elementName, variableName, validationFunction, indexValue, indexPosition) { 
    $(elementName).blur(function() { 
     var variableName = $(elementName).val(); 
     if(validationFunction(variableName) == true) { 
      if(variableName.lastIndexOf(indexValue) != indexPosition) { 
       variableName = variableName.replace(indexValue, ''); 
       $(elementName).val(indexValue + variableName); 
      } 
     } 
     else { 
      variableName = ''; 
      $(elementname).val(variableName); 
     } 
    }); 
} 

在我会打电话的功能类似如下:

validateElements('#country_code', 'countryCode', 'validateNumber', '+', 0); 
+4

而你的问题是? – DavidGouge 2011-05-12 14:09:51

+0

题目问题,我也很困惑 – locrizak 2011-05-12 14:14:20

+0

问题是:我该如何做这项工作?就目前而言,事实并非如此。 – Tony 2011-05-12 14:27:40

回答

0

尝试改变它,以便您按以下方式调用您的功能:

validateElements($('#country_code'), 'countryCode', 'validateNumber', '+', 0); 

并改变你的功能:

function validateElements(obj, variableName, validationFunction, indexValue, indexPosition) { 
    obj.blur(function() { 
     var variableName = obj.val(); 
     if(validationFunction(variableName) == true) { 
      if(variableName.lastIndexOf(indexValue) != indexPosition) { 
       variableName = variableName.replace(indexValue, ''); 
       obj.val(indexValue + variableName); 
      } 
     } 
     else { 
      variableName = ''; 
      obj.val(variableName); 
     } 
    }); 
} 
+0

试了一下,仍然没有运气。 – Tony 2011-05-12 14:26:42

+0

要做的最好的事情是一次注释一行代码行,运行代码并查看它何时有效。当你说“它不起作用”时,你的意思是模糊事件被调用,而事件内部的东西不正确,或者模糊事件从未被调用? – 2011-05-12 14:58:37