【问题标题】:dynamic variables in an iframeiframe 中的动态变量
【发布时间】:2015-06-03 21:00:19
【问题描述】:
我正在尝试使用 HTML5 地理编码将动态纬度和经度传递到 iframe。这是我所能得到的。我不能完全让纬度和经度进入 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>
【问题讨论】:
标签:
javascript
html
iframe
geolocation
【解决方案1】:
您查看过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>');
});
【解决方案2】:
你应该先定义你的 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>