iframe中的动态变量

时间:2015-06-03 21:00:20

标签: javascript html5 iframe geolocation

我正在尝试使用HTML5地理编码将动态lat和long传递给iframe。这是我能得到的。我无法让lat和lon进入iframe src。

如何正确地将变量传递到iframe?

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">

function myLat(position) {
    text(position.coords.latitude);
}

function myLon(position) {
    text(position.coords.longitude);
}

document.write('<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="http://forecast.io/embed/#lat='+myLat+'&lon='+myLon+'&name=Your Location"> </iframe>');

</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

您应首先定义iframe,然后从JavaScript设置其来源:

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


<script>
function myLat(position) {
    text(position.coords.latitude);
}

function myLon(position) {
    text(position.coords.longitude);
}

document.getElementById("forecast_embed").src = "http://forecast.io/embed/#lat="+myLat+"&lon= "+myLon+"&name=Your Location";
</script>

答案 1 :(得分:0)

您是否查看了geolocation的文档?像下面这样的东西会做你想要的:

navigator.geolocation.getCurrentPosition(function(position) {

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    document.write('<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%"' +
        'src="http://forecast.io/embed/#lat=' + lat + '&lon=' + lon + '&name=Your Location"> </iframe>');
});