jQuery/JS:获取当前URL的父目录

10

3
小小的指正...那不是一个“目录”。它是资源的URL的一部分。它可能映射到服务器上的目录,但URL本身没有目录,因为HTTP不是文件系统。 - David
感谢提供的信息,非常感激。 - Eduardo Go
6个回答

12
var myURL = "http://www.site.com/example/index.html";
var myDir = myURL.substring( 0, myURL.lastIndexOf( "/" ) + 1);

5
$(location).prop("href").split("/").slice(0,-1).join("/")

当前页面的演示过程:

  1. $(location)

    {
        "ancestorOrigins": {
        },
        "hash": "",
        "host": "stackoverflow.com",
        "hostname": "stackoverflow.com",
        "href": "https://dev59.com/PmMm5IYBdhLWcg3wlv0K",
        "origin": "https://stackoverflow.com",
        "pathname": "/questions/17497045/jquery-js-get-current-url-parent-directory",
        "port": "",
        "protocol": "https:",
        "search": ""
    }
    
  2. $(location).prop("href")

    https://dev59.com/PmMm5IYBdhLWcg3wlv0K
    
  3. $(location).prop("href").split("/")

    [
        "https:",
        "",
        "stackoverflow.com",
        "questions",
        "17497045",
        "jquery-js-get-current-url-parent-directory"
    ]
    
  4. $(location).prop("href").split("/").slice(0,-1)

    [
        "https:",
        "",
        "stackoverflow.com",
        "questions",
        "17497045"
    ]
    

    ※ The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Use negative numbers to select from the end of an array.

  5. $(location).prop("href").split("/").slice(0,-1).join("/")

    https://dev59.com/PmMm5IYBdhLWcg3wlv0K
    

注释和参考资料:

  • location: location对象包含有关当前URL的信息。
  • href: 当前页面的完整URL。
  • .prop(): 获取元素属性的值。
  • .split(): 该方法用于将字符串拆分为子字符串数组,并返回新的数组。
  • .slice(): 该方法返回一个由数组中选定元素组成的新数组对象。
  • .join(): 该方法将数组的元素连接成一个字符串,并返回该字符串。

4
您能否详细阐述一下,以便其他程序员理解它是如何帮助解决问题的? - Nagama Inamdar
这是一个更好的答案,因为你可以轻松地获取祖父母等信息。 - Moradnejad

4

2
以下似乎有效。
new URL(".", "http://example.com/folder/subfolder/file.js")

1

小提琴

var a = "http://www.site.com/example/index.html";
var b = a.substring(0, a.lastIndexOf('/'))+"/";

1
一条正则表达式也可以实现同样的功能,但在这个例子中,正则表达式不是最简单的解决方案。
var url = "http://www.site.com/example/index.html";
var newUrl = url.match(/^(.*[\\\/])/)[1];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接