如何在不同状态下访问 DOM 中的 <a> 的 'href' 属性?

How to access the 'href' property of an <a> in the DOM at different states?

本地提供的测试页:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<a href="http://127.0.0.1:8000/test2" id="good">good</a>
<a href="/test1" id="bad">bad</a>

在Firebug的命令行中:

goods=$('a[href^=http]');
bads=$('a:not([href^=http])');

goods[0].href 输出 "127.0.0.1:8000/test1",符合预期

bads[0].href 输出 "127.0.0.1:8000/test2",令人惊讶。我预计 "/test1".

似乎 Firebug 或 Firefox 试图通过显示假定的主机名来帮助我。

如何访问添加到控制台输出中 URL 路径的主机名值?

.href 总是 return 绝对值 URL。使用 bads.attr('href') 而不是 bads[0].href。这应该return "/test1".

JSFiddle

URL specification defines that the href property returns the full URL. See also the documentation for URLUtils.href on MDN.

如果您想要访问在属性中看到的值,您需要通过 getAttribute().

读取属性的值

你的情况是:

bads=$('a:not([href^=http])');
bads[0].getAttribute('href');

或通过jQuery:

bads.attr('href');

有关 URL 的其他信息可通过元素本身直接访问,因为它包括上述 URLUtils 接口。因此,要获取主机名(在您的示例中为 127.0.0.1),您需要这样写:

bads=$('a:not([href^=http])');
bads[0].hostname;