Jquery .data()在ajax成功中无效

时间:2015-05-22 12:37:14

标签: javascript jquery ajax google-maps

我有一个AJAX调用,可以正常工作并附加返回的HTML。问题是我无法附加数据而且我不知道原因。

一切正常 - 即使标记放在地图上 - 数据除外。

这就是我所拥有的:

$.ajax({
    url: '/Trip/TrainCard',
    type: 'POST',
    data: modeldata,
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        $(".traincards").append(data);

        var traincard = $(data).find(".traincard");
        var id = $(traincard).attr("id");
        id = id.split("_")[1];

        var icon = $(traincard).data().iconurl;

        //Create some marker options
        var markerOptions = CreateMarkerOptions(id, null, null, null, null, null, true, null, icon, map, null, place.geometry.location, null, true, null, "", null, null, ICONSCALE.TYPE.MARKER.MIDPOINT);

        //Create a marker
        var marker = CreateMarker(markerOptions, "", $(traincard).data().color);

        marker.setPosition(place.geometry.location);
        marker.setVisible(true);

        //does nothing!
        $(traincard).data({ marker: marker });

        //Add the city to the list on the map
        addNewCityToMapList(id, place.name)
    },
    error: function (xhr, ajaxOptions, thrownError) {
        ShowUserMessage("Error: " + xhr.status + " " + thrownError);
    }
});

由于某些原因,我无法在traincard上添加标记,请参阅$(traincard).data({ marker: marker });

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

问题是因为您在返回的data()变量上使用data方法,而不是从DOM附加到DOM的元素。尝试在返回的数据上设置所需的属性,然后将其附加到DOM。试试这个:

success: function (data) {
    var $data = $(data);
    var $traincard = $data.find(".traincard");
    var id = $traincard.attr("id").split("_")[1];
    var icon = traincard.data('iconurl');
    var markerOptions = CreateMarkerOptions(id, null, null, null, null, null, true, null, icon, map, null, place.geometry.location, null, true, null, "", null, null, ICONSCALE.TYPE.MARKER.MIDPOINT);
    var marker = CreateMarker(markerOptions, "", $traincard.data('color'));
    marker.setPosition(place.geometry.location);
    marker.setVisible(true);
    $traincard.data('marker', marker)
    $data.appendTo(".traincards"); // append the element _after_ you've set its attributes

    //Add the city to the list on the map
    addNewCityToMapList(id, place.name)
},