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

标签 javascript jquery leaflet magnific-popup

我有一个函数,可以在标记放入 map 后获取标记的坐标:

$(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 函数并仍然将其作为字符串?

最佳答案

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

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

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.
        */
      }
    }
  });
}

关于javascript - 字符串传递给另一个函数后变成对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872659/

相关文章:

javascript - 预过滤条件 - deep-diff Node.js

c# - SignalR 阻止 chrome UI?

ember.js - 在传单弹出窗口中渲染 View 或 Handlebars 模板

leaflet - 就地更新传单 GeoJSON 功能

jquery - Ember.js 对 JQuery 的依赖无法通过 Rails 得到满足

javascript - Angular 2 中的 Leaflet + Google - 瓷砖顺序错误

javascript - 为什么下面的 `exports = { z: function() {} };` 不起作用

javascript - 选中/取消选中复选框时,在数组中添加/删除数字

javascript - 使用 jquery 访问 gridview 内的隐藏字段并更新它?

javascript - Jquery First() 不工作