0

我做一个脚本。得到元素的href。但我只想要这个网址的最后一部分。我做这个:

var newURL = $(".list-portfolio a").attr("href");
    pathArray = newURL.split( '/' ),
        secondLevelLocation = pathArray[0];

    var newPathname = "";
    for ( i = 3; i < pathArray.length; i++ ) {  
      newPathname += "/";
      newPathname += pathArray[i];
    }

这导致/portfolio/ruimzicht.html这几乎是好的。我怎样才能删除第一个/。

你有任何改进代码的技巧吗?

4

4 回答 4

2

为什么不使用数组函数?

var pathArray = ["portfolio", "ruimzicht.html"];

// build a string by inserting a forward slash between all elements
pathArray.join("/");

// results in: portfolio/ruimzicht.html

如果你只是对最后一部分感兴趣,你可以把它缩小成一个衬里:

url.split("/").pop(); // yields "ruimzicht.html"
于 2012-08-09T16:50:04.777 回答
0

尝试使用它来避免第一次连接/

for ( i = 3; i < pathArray.length; i++ )
{  
    if(i != 3)
        newPathname+= "/";

    newPathname += pathArray[i];
}
于 2012-08-09T16:46:33.873 回答
0
newPathname = newPathname.trim("/");
于 2012-08-09T16:50:22.477 回答
0

I believe that doing the URL parsing this way makes the code brittle and bug prone. Instead of doing all the string splitting and/or regex operations, you can use a 3rd party plug-in like jQuery-URL-Parser, which allows you to get the URL from an element and decomposes it into different parts, so that you can access the filename or the host name etc. Here is an example on how to use it in your case.

var url = $.url($(".list-portfolio a").attr("href"));
url.attr('file'); // this will give you ruimzicht.html

It makes the code simpler and easier to read and maintain.

于 2012-08-09T16:51:51.270 回答