Javascript .pathname IE quirk?

2020-02-09 00:07发布

问题:

Consider the following Javascript:

var anchors = document.getElementsByTagName('a');
for(var i=0; i < anchors.length; i++)
{
    alert(a.pathname);
}

When I run this on a page that contains links in the format "http://foo.com/bar", in IE8 I get back a string that looks like "bar". In Safari, Chrome, Firefox, I get back something like "/bar" (note the leading forward slash).

Is IE at fault here, what's the deal?

回答1:

The W3C standard on the window object - including the location interface - is dated 07 April 2006, ie it was specified after actual implementations had been around for years.

The standard reads:

pathname

This attribute represents the path component of the Location's URI which consists of everything after the host and port up to and excluding the first question mark (?) or hash mark (#).

This means the leading slash should be included, which is consistent with Mozilla's implementation.

The MSDN doc on the location object doesn't mention what the property contains, but a page on the VBScript location object has an example consistent with your discovery.

As said page is ©1996 - ten years before the W3C got involved - it's hardly fair to say that IE is at fault, but I'd still consider it a bug.



回答2:

The odd thing about this behavior is that window.location.pathname returns the leading slash (after the hostname) in all versions of IE, same as all other browsers.

It is only the location object of a hyperlink ('a element') that returns the path without the slash in IE (and Opera as well).



回答3:

Use getAttribute if your'e looking for an easy way to overcome this.

See: Spec, MDN

Example

HTML:

<a href="/foo" id="foo">

JS:

document.getElementById("foo").getAttribute("href");

This will return the leading slash as well ("/foo"). And it's supported on all browsers that has DOM-Level-2 implemented correctly.