![](/img/trans.png)
[英]What is the correct way of calling an internal function using the module pattern in Javascript
[英]Correct way of calling a javascript function
我正在嘗試通過添加國家名稱的提取來擴展此網站上的google maps標記示例。
由於Google Maps返回一個包含每個地址詳細信息的數組,因此我需要遍歷該數組以查找條目,例如“ country”。 由於我想重用這段代碼,因此我創建了一個函數。
但是我不確定如何正確調用此函數(在這里調用find(components,item) )。
我沒有從find函數得到任何回報。 如何從select函數中正確調用find函數? * 為什么我得到空收益會有其他錯誤? *
感謝您的想法和建議!
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
components: item.address_components,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
// address_component selection
find: function(components, item) {
for(var j=0;j < components.length; j++){
for(var k=0; k < components[j].types.length; k++){
if(components[j].types[k] == "country"){
return components[j].long_name;
}
}
}
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#latitude").val(ui.item.latitude);
$("#longitude").val(ui.item.longitude);
$("#country").val(this.find(ui.item.components, "country"));
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});
find()
函數在autocomplete
選項對象中定義。
如果要訪問find函數,則必須在自動完成選項之外定義它或獲取指向它的指針:
var find = $(event.target).data("autocomplete").options.find;
這是因為jQuery使用附加到偵聽器的元素更改了函數的上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.