2012-11-08 35 views
2

在ajax成功函數上,我使用vktemplate將一些項目放入下拉列表中。但是,我想附加一些數據給他們,以便當用戶選擇地址的名稱時,我可以快速地從jquery數據對象中提取整個地址。jQuery數據給出錯誤:undefined

success: function (returnedData) { 

    $('.vendor_address_select').vkTemplate('templates/vendor_addresses_by_sector_dropdown_template.tmpl?<?=time()?>', returnedData, function() { 

     $.each(returnedData, function (key, val) { 
      var id = val.id; 

      //dropdown option looks like this: 
      //<option id="vendor_address_id_22">company1</option> 
      $('#vendor_address_id_' + id).data('address', { 
       'vendorName': val.vendor_name, 
       'address1': val.address1, 
       'address2': val.address2, 
       'city': val.city, 
       'state': val.state, 
       'zip': val.zip 
      }); 

     }); 

    }); 
} 

是給我這個錯誤 遺漏的類型錯誤:無法調用方法的不確定

'分裂',當我嘗試訪問這樣的數據:

$(document).ready(function() { 
    $('.vendor_address_select').change(function() { 

     var selectedAddress = $('option:selected', this); 
     console.log(selectedAddress.data()); 

    }); 
}); 

我如何濫用jquery的data()

模板文件:

<% for (var i = 0 in o) { %> 
<option id="vendor_address_id_<%=o[i].id%>"> 
<%=o[i].vendor_name%></option> 
<% } %> 

回答

4

你必須使用.data()像這樣

$(document).ready(function() { 
    $('.vendor_address_select').change(function() { 

     var selectedAddress = $('option:selected', this); 
     console.log(selectedAddress.data('address')); 

    }); 
}); 
+0

真棒時指定鍵 '地址'!非常感謝你! – 1252748