所以我想做一個可以代替iframe的src的函數。在iframe中會有一個有兩個地方的地圖。在html代碼中,有兩種形式的地點ID-s。如何用javascript更改iframe源代碼片段?
我只是不能得到這個工作。
下面是HTML代碼:
<div id="start">
<label for="startLocation">Start location ID:</label>
<input type="text" id="startLocation" name="startLocation" value="" ><br><br>
</div>
<div id="dest">
<label for="destination">Destination ID:</label>
<input type="text" id="destination" name="destination" ><br><br>
</div>
<button onclick="changeMap()">Show the map!</button><br><br>
</form>
<iframe id="map" width="600" height="450" frameborder="0" style="border:0" src="" allowfullscreen></iframe>
這將是功能:
function changeMap(){
//place IDs to put into url
var start = document.getElementById('startLocation').value;
var dest = document.getElementById('destination').value;
//pieces of the url
var mapSource1 = "https://www.google.com/maps/embed/v1/directions?origin=place_id:";
var mapSource2 = "&destination=place_id:";
var mapSource3 = "&key=AIzaSyDMtNzjQdNk-FX1hz7IWVcNiby1B8xiZeg";
var mapSource = mapSource1+start+mapSource2+dest+mapSource3;
//iframe
var iframe = document.getElementById('map');
//changing the src of the iframe
iframe.src = mapSource;
}
哇,謝謝!實際上我剛開始使用javascript和html,所以我不知道這些東西.. :)你寫道,腳本不應該低於表單,但如果JavaScript是在外部文件中,那怎麼可能發生?或者,將腳本放在HTML中會更好嗎?謝謝! – Ilka
@Ilka原諒我早些時候自相矛盾的評論。我剛刪除它。是的,如果您使用'onclick'來設置事件處理程序,您的腳本標籤必須首先顯示。不管它是否僅僅引用外部文件都沒關係。只需移動標籤_上方的'按鈕'。 請注意,即使您可以這樣做,也不推薦使用「onclick」。使用'document.onReady'和'addEventListener'被認爲是很好的做法。 PS:請記住'onclick'和'document.onReady'不能一起使用。 –