通过下拉菜单更改iframe src不会加载新的iframe

时间:2015-11-06 18:54:39

标签: javascript jquery html iframe src

我在这里玩了几个例子,但我似乎无法在没有“重置”下拉菜单的情况下加载新的iframe(选择没有价值的“选择度假村”选项)​​。有没有办法在选择新选项后动态更改iframe?

这是一个小提琴:http://jsfiddle.net/scdgw48g/

<h2>Your Powder Forecast</h2>
<p>Pick a location to see who's getting hit!</p>
<select id="selectResort">
<option>Pick Resort</option>
<option value="http://forecast.io/embed/#lat=42.3583&lon=-71.0603&name=Downtown Boston&font=inherit">Boston</option>
<option value="http://forecast.io/embed/#lat=39.6061&lon=-106.3571&name=Vail&font=inherit">Vail</option>
</select>
<button onClick="loadPages()">See Forecast</button>

<iframe id="myFrame" type="text/html" frameborder="0" height="245" width="100%" src=""> </iframe>

 <script>
    var urlSelect = document.getElementById('selectResort'),
    myFrame = document.getElementById('myFrame');
    function loadPages() {
    var loc = urlSelect.value;
    // You can also do -> myFrame.src = loc;
    myFrame.setAttribute('src', loc);
   }
 </script>

2 个答案:

答案 0 :(得分:2)

首先设置src = "",然后在最小延迟后,将其设置为您想要的src

documentation

function loadPages() {
    myFrame.src = "";
    setTimeout(function () {
        myFrame.src = urlSelect.value;
    }, 0);
}

答案 1 :(得分:1)

您需要在其中一个网址中添加参数,以便将它们彼此区分开来。我认为浏览器将它们视为相同的网址,因为它们都以http://forecast.io/embed/#lat=开头。请尝试以下方法。请注意我是如何将?different添加到第二个网址的:

<option value="http://forecast.io/embed/#lat=42.3583&lon=-71.0603&name=Downtown Boston&font=inherit">Boston</option>
<option value="http://forecast.io/embed/?different#lat=39.6061&lon=-106.3571&name=Vail&font=inherit">Vail</option>

这也可能是有意义的,虽然我不认为它适用于你的情况:

某些网站不允许将自己加载到iframe中。他们通过设置X-Frame-Options response header来完成此操作。当我将http://forecast.io网址更改为http://apple.comhttp://rogers.com时,一切正常。但是,当我将其更改为http://google.comhttp://microsoft.com时,Chrome会抛出以下错误。这是因为Microsoft和Google网站不允许将自己加载到外部网站上的iframe中。

Refused to display 'http://www.microsoft.com/fr-ca/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

相关问题