2016-02-25 38 views
0

所以我想做一個可以代替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; 


} 

回答

0

<button onclick="changeMap()">Show the map!</button><br><br> 

可能會造成問題。

首先,button元素,如果沒有給出type="button",則認爲是submit按鈕。所以每次按下按鈕時,表單都會被提交,瀏覽器開始加載不同的頁面,然後JavaScript有時間做很多事情。

其次,我看到你正在使用onclick附加事件處理程序。如果您的腳本在您的HTML中必須爲以上,form,則會導致changeMap未定義。我建議使用JavaScript,像這樣安裝的事件處理程序:

<button type="button" id="show-map">Show the map!</button><br><br> 
var btn = document.getElementById('show-map'); 
btn.addEventListener('click', changeMap); 

注意,因爲這是在這裏選擇button元素,無論是script標籤必須置於下面button(所以按鈕就在 - 不能選擇任何東西!),或者需要將JavaScript放在一個document.onReady函數中,這樣腳本纔會觸發,直到頁面加載完成(這意味着button將被完全加載)。

除非您使用的是document.onReady,否則script標記和button的順序確實很重要。如果script引用button,則button首先出現。如果button引用script,則script必須先出現。

包裝在某種document.onReady是常見的做法。 jQuery有一個功能($.ready),可以用來做到這一點,但如果你勇敢you can also do it without jQuery。請注意0​​不適用於較舊的IE。你可以使用polyfill it或使用jQuery。

+0

哇,謝謝!實際上我剛開始使用javascript和html,所以我不知道這些東西.. :)你寫道,腳本不應該低於表單,但如果JavaScript是在外部文件中,那怎麼可能發生?或者,將腳本放在HTML中會更好嗎?謝謝! – Ilka

+0

@Ilka原諒我早些時候自相矛盾的評論。我剛刪除它。是的,如果您使用'onclick'來設置事件處理程序,您的腳本標籤必須首先顯示。不管它是否僅僅引用外部文件都沒關係。只需移動標籤_上方的'按鈕'。 請注意,即使您可以這樣做,也不推薦使用「onclick」。使用'document.onReady'和'addEventListener'被認爲是很好的做法。 PS:請記住'onclick'和'document.onReady'不能一起使用。 –