【问题标题】:Using web page address to create src for image on page使用网页地址为页面上的图像创建 src
【发布时间】:2014-11-18 18:11:19
【问题描述】:

例如我有一个文件名为:/SW1A2AA.htm

在 HTML 中,我需要显示以下图像以及图像的来源以包含文件名(不带扩展名)。即:

<img src= "https://maps.googleapis.com/maps/api/staticmap?center=sw1a2aa&zoom=18&size=640x480">

显然,如果我需要对很多页面执行此操作,如果有办法修改搜索字符串以依赖文件名(不带扩展名)会更容易。

请告诉我有一种简单的方法可以产生该结果!

谢谢

【问题讨论】:

  • 那个静态地图中心应该是什么?因为现在,google 无法知道 sw1a2aa 代表什么位置。
  • 如果 URL 中有文件名,可以使用 JavaScript - window.location.pathname 从那里获取它,然后生成 src
  • amenadiel img src 工作正常,静态地图中心对于位置 'sw1a2aa' 是正确的
  • mgibala - 在这种情况下,我将如何在 src 中使用 window.location.pathname?

标签: html image google-maps src


【解决方案1】:

这是我为您的示例提供的解决方案 (SW1A2AA.htm)。空 src 属性无效,因此我们使用 //:00 - 您可以阅读有关此解决方案的更多信息here

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
</head>
<body>

<img id="map" src="//:0">


<script>
// grab the URL. I'm working locally so in my case it is /C:/Users/myLogin/Desktop/SW1A2AA.htm
var pageURL = window.location.pathname; 

// find the last position of the "/"
var fileNamePosition = pageURL.lastIndexOf("/"); 
// take file name and delete last 4 characters (SW1A2AA.htm -> SW1A2AA)
var fileName = pageURL.slice(fileNamePosition+1,-4);
// create src
var mapSrc = "https://maps.googleapis.com/maps/api/staticmap?center=" + fileName + "&zoom=18&size=640x480"; 

// update map src attribute
var map = document.getElementById("map");
map.setAttribute("src", mapSrc);


</script>
</body>
</html>

【讨论】:

  • 我尝试过

    将文件名写入 html 页面。 JavaScript 如下:
  • 是的,对不起!我尝试使用相同的 javascript 并在 和 <p id> 标签中调用它,但没有意识到你不能这样做!</p>
猜你喜欢
  • 2011-04-29
  • 2012-07-05
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
相关资源
最近更新 更多