从jQuery函数中检索多个值

时间:2013-09-10 10:15:57

标签: javascript jquery

如何使用下面提到的jQuery函数检索petKeysemployeeKey值?

var whenSelectDateFromCalendar = function () {
    initKeyValues();
    petKeys = ? employeeKey = ?
};


var initKeyValues = function () {
    var petKeys = $('#pets input:checked').map(function () {
        return $(this).val();
    }).get().join('+');
    var employeeKey = $('#employee input:checked').map(function () {
        return $(this).val();
    }).get().join('+');
}

2 个答案:

答案 0 :(得分:4)

您可以返回对象中的两个值。试试这个:

var whenSelectDateFromCalendar = function () {
    var keys = initKeyValues();

    // use the object returned above to set the vars here
    petKeys = keys.petKeys;
    employeeKey = keys.employeeKey;
};


var initKeyValues = function () {
    var petKeys = $('#pets input:checked').map(function () {
        return $(this).val();
    }).get().join('+');
    var employeeKey = $('#employee input:checked').map(function () {
        return $(this).val();
    }).get().join('+');

    // return the object containing both values
    return { 
        employeeKey: employeeKey,
        petKeys: petKeys
    }
}

答案 1 :(得分:1)

选项1 - 在对象中返回多个结果

var initKeyValues = function () {
    var petKeys = $('#pets input:checked').map(function () {
        return $(this).val();
    }).get().join('+');

    var employeeKey = $('#employee input:checked').map(function () { return $(this).val(); }).get().join('+');}

    return {"petKeys": petKeys,  "employeeKey": employeeKey}
};

var whenSelectDateFromCalendar = function () {
    var result = initKeyValues();

    petKeys = result.petKeys;
    employeeKey = result.employeeKey;   

    // or even...

    petKeys = result["petKeys"];
    employeeKey = result["employeeKey"];
};

选项2:在数组中返回多个结果

var initKeyValues = function () {
    var petKeys = $('#pets input:checked').map(function () {
        return $(this).val();
    }).get().join('+');

    var employeeKey = $('#employee input:checked').map(function () { return $(this).val(); }).get().join('+');}

    return [petKeys, employeeKey];
};

var whenSelectDateFromCalendar = function () {
    var result = initKeyValues();

    petKeys = result[0];
    employeeKey = result[1];
};