javascript链接分析混乱
我有一个html链接标签,它有一个“href”属性,我想获取域名,通过“host”方法获取我想要的内容是可以的,但我发现非常奇怪,看看这个例子javascript链接分析混乱,javascript,Javascript,我有一个html链接标签,它有一个“href”属性,我想获取域名,通过“host”方法获取我想要的内容是可以的,但我发现非常奇怪,看看这个例子 <a href="http://stackoverflow.com/questions/ask" id="test"></a> <script> x=document.getElementById("test"); alert(x.href.host+" , "+x.host); </script>
<a href="http://stackoverflow.com/questions/ask" id="test"></a>
<script>
x=document.getElementById("test");
alert(x.href.host+" , "+x.host);
</script>
x=document.getElementById(“测试”);
警报(x.href.host+,“+x.host);
天哪!结果是:
-x.href.host:取消查找
-x.host:stackoverflow.com
我想知道为什么JS把X看作一个链接,即HREF值,但是没有考虑X.HREF值作为链接
因为
x.href
是字符串,它没有名为host
的属性
因此,请尝试:
x=document.getElementById("test");
var host=x.getAttribute('href');
var pos=/:\/\//.test(host)?host.indexOf('/',7):host.indexOf('/');
host=host.substring(0,pos);
就这样。
主机将存储在变量
host
@Sherif eldeb上如果这解决了您的问题,请告诉我