字符串在传递给另一个函数后变成了对象?

时间:2016-03-08 16:26:00

标签: javascript jquery leaflet magnific-popup

我有这个函数,它在标记被放入地图后获取标记的坐标:

$(function() {
$( "#add-marker" ).draggable({
    containment: "map",
    helper: "clone",
    start: function(evt, ui) {
        $('#navbar').fadeTo('fast', 0.6, function() {});
    },
    stop: function(evt, ui) {

        // Turning coordinates into a string and then removing unwanted characters
        var string = String(map.containerPointToLatLng([ui.offset.left, ui.offset.top]));

        string = string.replace('LatLng(', '');
        string = string.replace(' ', '');
        string = string.replace(')', '');
        console.log(typeof string); // ---> Shows my coordinates
        addProperty(string);
    }
});
});

问题是,当我传递“string”时,它会被转换为一个对象:

function addProperty(coords){
$.magnificPopup.open({
    tLoading:"Loading...",
    modal:false,
    showCloseBtn: true,
    closeBtnInside: true,
    type:'inline',
    alignTop:false,
    items:{src: $('#test-popup')},
    callbacks: {
        open: function(coords) {
            console.log(typeof $(this).data(coords)); // ---> Shows object
            $('#coords').val($(this).data(coords));
        }
    }
});
}

如何将“string”传递给addProperty函数并仍将其作为字符串?

2 个答案:

答案 0 :(得分:3)

在第二个示例中,您处理来自coords回调的open值,而不是来自高级函数addProperty的值。

要解决此问题,只需从coords回调中重命名open变量名称:

function addProperty(coords) {

  $.magnificPopup.open({

    callbacks: {

      open: function(newCoords) {
        /* 
           Here, you can access coords wich is still the string version,
           or newCoords wich is the new object returned by the callback.
        */
      }
    }
  });
}

答案 1 :(得分:1)

如果您访问lat返回的lng对象的L.LatLngcontainerPointToLatLng属性,您将会更加轻松:

stop: function(evt, ui) {

    var ll = map.containerPointToLatLng([ui.offset.left, ui.offset.top]);

    var str = '' + ll.lat.toFixed(4) + ',' + ll.lng.toFixed(4);

    addProperty(str);
}