我有一个函数,可以在标记放入 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/