Javascript 如何将重复的代码块转换为函数

Javascript 如何将重复的代码块转换为函数,javascript,jquery,function,Javascript,Jquery,Function,我已经有了一系列代码,这些代码将在联系人表单中的绝大多数输入项上运行;为了代码行的缘故,我想让它作为一个函数运行。以下是该块的一个示例: $('#country_code').blur(function() { var countryCode = $('#country_code').val(); if(validateNumber(countryCode) == true) { if(countryCode.lastIndexOf('+') != 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);

尝试更改它,以便按如下方式调用函数:

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);
        }
    });
}

问题的标题,我很困惑,问题是:我如何才能使这项工作?就像现在一样,它没有。尝试一下,还是没有运气。最好的办法是一行一行地注释掉代码行,运行代码,看看它什么时候起作用。当你说“它不工作”时,你是说正在调用模糊事件,而事件中的某些内容不正确,还是说从未调用过模糊事件?