2

在 ajax 成功函数上,我使用vktemplate将一些项目放入下拉列表中。但是,我想将一些数据附加到它们,以便当用户选择地址名称时,我可以快速从 jquery 数据对象中提取整个地址。

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

        });

    });
}

给我这个错误 Uncaught TypeError: Cannot call method 'split' of undefined

当我尝试访问这样的数据时:

$(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

1 回答 1

4

.data()像这样使用时必须指定键“地址”

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

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

    });
});
于 2012-11-08T21:47:33.500 回答