通过Jquery Every()设置对象的值

时间:2014-07-11 18:06:30

标签: javascript jquery

我正在尝试遍历object.key(newPickup)并将object.key的值设置为等于表单中指定的值。然而,当我调用该对象时,所有项目都是未定义的,我可以完成而不会抛出任何错误。我设置了一个已经装好的小提琴,我希望你们中的一个才华横溢的人能让我知道我搞砸了哪里。提前致谢。

小提琴:http://jsfiddle.net/kevinmota/X7MW6/

<button id="startPickup">Schedule Pickup</button>
<div id="pickupWrap"></div>


function Pickup(pickupDate, clinicName, phoneNumber, qtySpec, fedexConfirm){
        this.pickupDate = pickupDate;
        this.clinicName = clinicName;
        this.phoneNumber = phoneNumber;
        this.qtySpec = qtySpec;
        this.fedexConfirm=fedexConfirm;
    }
//The Pickup Object
var newPickup = new Pickup();

//Click the button to make the form 
$("#startPickup").click(function(){
    //Empty if exists
    $("#pickupWrap").empty();
    //Make the inputs
    $.each(newPickup, function(key,value){
        $('#pickupWrap').append("<label for=\""+key+"\">"+key+": </label><input type=\"text\" id=\""+key+"\" class=\"pickupInput\"><br>");
    });
    //Make the button
    $('#pickupWrap').append("<button id='submitPickup'>Submit Pickup</button");

    //Capture the form inputs from pickup
    $("#submitPickup").click(function(){
    console.log("click");

    //Get Values and Indexes
    $('.pickupInput').each(function(){
        var pickupIndex = $(this).attr("id");
        var pickupValue =$(this).val();

        console.log(pickupIndex+" | "+ pickupValue);

        //Set newPickup to appropriate value
        $.each(newPickup, function(key, value){
            if (key === pickupIndex) {
                console.log("we have a match");
                value = pickupValue;
            };
        })
    });
    console.log(newPickup);

});
});

1 个答案:

答案 0 :(得分:0)

value = pickupValue不是您想要的,您需要指定object[key]并设置:

$.each(newPickup, function(key, value){
    if (key === pickupIndex) {
        console.log("we have a match");
        newPickup[key] = pickupValue;
    };
})