2016-04-09 20 views
1

我有一個主要的PHP文件,其中包含8個PHP文件。我使用bootstrap類「Modal」,並在每個模式中使用谷歌地圖。所以我有不同的ID來顯示谷歌地圖,但功能是相同的。這意味着,當每個模式彈出窗口中的一個時,該功能將被觸發並顯示谷歌地圖。我爲每個ID實現了8種不同的功能。如何使用不同的ID來觸發一個函數

我想要的是,有沒有什麼辦法可以通過一個函數來實現?

這麼說的更清楚,如果與id = 1模式彈出窗口,它顯示了谷歌地圖在<div id="location_incident1">,如果用id = 2模式彈出窗口,它顯示了在<div id="location_incident2">谷歌地圖,如果模態彈出窗口與id = 3,它顯示了谷歌地圖在<div id="location_incident3">和等等。

這裏是我的代碼簡單:

function locationOfIncident3(current) 
{ 
    var lat = current.coords.latitude; 
    latIncident = lat; 
    var lon = current.coords.longitude; 
    lonIncident = lon; 
    var mapOption={ 
     center: new google.maps.LatLng(lat, lon), 
     zoom: 15, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map3 = new google.maps.Map(document.getElementById('location_incident3'), mapOption); 

    marker3 = new google.maps.Marker({ 
     position: new google.maps.LatLng(lat, lon), 
     map: map3, 
     draggable: true, 
     title: 'Location of Incident' 
    }); 

    google.maps.event.addListener(marker3, 'dragend', function(res){ 
     latIncident = res.latLng.lat(); 
     lonIncident = res.latLng.lng(); 
     getAddress3(latIncident, lonIncident); 
    }); 
} 
+2

的simpy通過ID的功能作爲第二個參數... – CBroe

+0

任何理由'latIncident ','map3',...需要是全局變量而不是'var map3',...? – Aprillion

回答

0

如果您不需要保留的功能外map3marker3,...變量,你應該使用局部變量,即var mapvar market。 ..

編號的字符串可以動態使用+連接運算符這樣創建:

function locationOfIncident(n, current) { 
    ... 
    var map = new google.maps.Map(document.getElementById('location_incident' + n), mapOption); 
    ... 
} 

你可以重構調用locationOfIncident1locationOfIncident2 ...用正則表達式在文本編輯器替換:locationOfIncident(\d+)\s*\( =>locationOfIncident\($1,

相關問題