【问题标题】:Writing .htm file name to the contents of the file in HTML将 .htm 文件名写入 HTML 中的文件内容
【发布时间】:2014-11-07 13:33:24
【问题描述】:

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

在 HTML 中,我需要显示 Google 搜索该文件名的结果的链接。即:

https://www.google.co.uk/?gfe_rd=cr&ei=6MhcVOGVHMnH8gej8oCQDQ&gws_rd=ssl#q=page1

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

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

谢谢

【问题讨论】:

  • 那我可以用什么,我可以处理.js,尽管我一直在尽可能地避免。我可以在该字符串的末尾调用一个 .js 文件来修改打开时的链接吗?
  • 如果我理解你的问题,你不能只用 HTML 来做到这一点。
  • 那么如何使用 .js 进行编码?
  • 只是添加一个细节:如果您运行的服务器支持的话,这也可以使用像 PHP 这样的服务器端语言来完成。

标签: javascript html filenames


【解决方案1】:

因为您提供的是静态 html 页面,所以任何“活动”行为(例如在内容中自动重用文件名)都需要在客户端运行时发生。这意味着Javascript:

<!-- In your html, use an ID tag to make the link easily selectable with javascript...--> 
<a id="googleSearchLink" href="#">Search Google for the name of this file</a>

然后在正文内容的底部(以便在呈现标记后发生)添加:

<script>
  // Grab everything after the last "/" from the location bar...
  var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);

  // Chop off the last "." and everything right of it...
  var withoutExtension = filename.replace(/\.[^/.]+$/, "");

  // Build the link destination as a string...
  var hrefTargetForGoogleLink = "https://www.google.co.uk/#q=" + withoutExtension;

  // Finally, set the link destination
  googleSearchLink.href = hrefTargetForGoogleLink;    

</script>

【讨论】:

  • 谢谢,您知道如何在 中使用文件名吗?
  • hoverbikers 回答了您的问题。如果它满足您的需要,请接受他的回答,并为您的新问题创建一个新问题。
猜你喜欢
  • 1970-01-01
  • 2016-06-05
  • 2016-09-28
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 2010-11-09
  • 1970-01-01
相关资源
最近更新 更多