A test page, served locally:
<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>
In Firebug's command line:
goods=$('a[href^=http]');
bads=$('a:not([href^=http])');
goods[0].href
outputs "127.0.0.1:8000/test1"
, as expected
bads[0].href
outputs "127.0.0.1:8000/test2"
, surprisingly. I expected "/test1"
.
It seems Firebug or Firefox is trying to help me by showing me the assumed hostname.
How can I access the host name value, which is added to the URL path in the console output?
答案 0 :(得分:3)
.href
always returns the absolute URL. Instead of bads[0].href
, use bads.attr('href')
. This should return "/test1"
.
答案 1 :(得分:2)
href
属性返回完整网址的URL specification defines。另请参阅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;