2014-07-11 103 views
0

我試圖遍歷object.key(newPickup)並將object.key的值設置爲等於窗體中指定的值。但是我可以在不拋出任何錯誤的情況下完成任務,但當我調用對象時,所有項目都是未定義的。我設置了一個已經加載的小提琴,我希望你們中的一個有才華的小人可以讓我知道我搞亂了什麼。提前致謝。通過jquery設置對象的值Each()

小提琴: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); 

}); 
}); 

回答

0

value = pickupValue是不是你想要的,你需要指定object[key],並設置:

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