【问题标题】:Jquery to get the name of the current html filejquery获取当前html文件的名称
【发布时间】:2012-10-30 07:35:15
【问题描述】:

如果您在http://www.cnn.com/2012/11/09/opinion/brown-pakistan-malala/index.html 上,您可以让Jquery 获取index.html 吗?

或者如果您在http://www.washingtonpost.com/politics/decision2012/supreme-court-to-review-key-section-of-voting-rights-act/2012/11/09/dd249cd0-216d-11e2-8448-81b1ce7d6978_story.html 上返回dd249cd0-216d-11e2-8448-81b1ce7d6978_story.html?

对于非扩展定义的页面,例如当前的http://stackoverflow.com/questions/13317276/jquery-to-get-the-name-of-the-current-html-file,它是否可以返回“目录”结构中的最后一个“文件”,例如:jquery-to-get-the-name-of-the-current-html-file

【问题讨论】:

  • 如果当前页面只是http://stackoverflow.com/怎么办?你只想要“stackoverflow.com”吗?
  • 好澄清,是的,路径名的最后一个就是我要找的
  • 我正在使用此代码 document.location.pathname.match(/[^\/]+$/)[0] 但是当我在我的基本链接中时,例如 http://stackoverflow.com/ 它正在抛出控制台出错,有什么方法可以验证吗?

标签: javascript jquery html


【解决方案1】:

虽然不是 JQuery,但您可以使用以下方式访问它:

document.location.href.match(/[^\/]+$/)[0]

或

document.location.pathname.match(/[^\/]+$/)[0] 在不需要锚点/哈希标签 (#) 的情况下。

【讨论】:

  • 我正在使用此代码 document.location.pathname.match(/[^\/]+$/)[0] 但是当我在我的基本链接中时,例如 http://www.cnn.com 它正在抛出控制台出错,有什么方法可以验证吗?
【解决方案2】:
function getCurentFileName(){
    var pagePathName= window.location.pathname;
    return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);
}

【讨论】:

    【解决方案3】:
    location.pathname.split('/').slice(-1)[0]
    

    【讨论】:

      【解决方案4】:

      不需要 jQuery。这将为您提供 URL 路径的最后一段(最后一个斜杠之后的位):

      var href = document.location.href;
      var lastPathSegment = href.substr(href.lastIndexOf('/') + 1);
      

      【讨论】:

      • 非常适合我!!
      猜你喜欢
      • 2022-11-18
      • 2015-04-10
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 2011-10-20
      • 2011-01-04
      相关资源
      最近更新 更多