[英]Passing arguments to a callback function in javascript
我们有这样的场景,我们有多个<input type="text"/>
框,我们在其中绑定自动建议(BING 地图),如下所示。
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () {
var options = {
maxResults: 4,
map: map
};
var manager = new Microsoft.Maps.AutosuggestManager(options);
var callback = {
selectedAddedDestination : selectedAddedDestination.bind({})
}
callback.selectedAddedDestination['pos'] = destinationIndex;
manager.attachAutosuggest('#destination'+destinationIndex+'', '#divAddDestination', callback.selectedAddedDestination);
});
其中 '#destination1" 或 #destination2 是<input type="text">
元素的 ID。我们有一个 function selectedAddedDestination,它由 Bing Maps 框架调用并接受自动建议的结果。但是,结果不包含<input type="text">
触发了事件。
function selectedAddedDestination(suggestionResult) {
var func = selectedAddedDestination;
var position = func['pos']
map.entities.clear();
map.setView({ bounds: suggestionResult.bestView });
........
}
我尝试将属性“pos”添加到 function。但是,它不可访问。 我还需要 function 的多个实例,每个文本框都带有“pos”属性,因此需要 function。
如果有解决方案,请告诉我。
你可以像这样使用 JavaScript 闭包来做到这一点:
Microsoft.Maps.loadModule("Microsoft.Maps.AutoSuggest", function () {
var options = {
maxResults: 4,
map: map,
};
var manager = new Microsoft.Maps.AutosuggestManager(options);
manager.attachAutosuggest(
"#destination" + destinationIndex + "",
"#divAddDestination",
selectedAddedDestination(destinationIndex)
);
});
function selectedAddedDestination(destinationIndex) {
return function (suggestionResult) {
map.entities.clear();
map.setView({ bounds: suggestionResult.bestView });
// Do what you want with destinationIndex
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.