2016-07-01 17 views
0

当我们点击一​​个<a>标签时,浏览器会被重定向到相应的页面,但有一些细节。考虑以下示例:如何获取浏览器在点击链接时将遵循的URL?

<a href="../onepage.html">One Page</a> 
<a href="http://example.com/onepage.html">One Page</a> 
<a href="onepage">One Page</a> 
<a href="onepage.html">One Page</a> 

当我们使用浏览器访问此类页面时,它将在某种意义上转换这些页面。如果其所在页面的地址为http://www.example.com/pages/somepage.html,则第一个将被翻译为重定向到http://www.example.com/onepage.html,第二个将保持原样,第三个将被翻译为http://www.example.com/onepage的重定向,并且最后一个也将是第三。

我的问题是:如何使用jQuery获取这些URL的“翻译版本”?这不是href,因为这会提供“原样”信息。

我们如何才能用jQuery获得浏览器实际遵循的URL,如果点击链接?

回答

0

你在找什么是如何将相对链接转换为绝对链接。我认为这个问题已经以多种形式被回答this answer

而不是其网址输入,就可以使用jQuery选择得到说使用$('a')[0]第一<a>标签(或使用您喜欢的jQuery的方法),并用其作为链接解决方案中使用的link变量。

0

你可以在jQuery中使用.prop('href')。这是.prop().attr()之间有所不同的情况之一。 .attr()返回DOM元素的原始属性,但.prop返回解析URL所产生的href属性。

在平凡的Javascript这些将是element.hrefelement.getAttribute('href')

$("a").each(function() { 
 
    console.log('.attr: ' + $(this).attr('href') + ' .prop: ' + $(this).prop('href')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="../onepage.html">One Page</a> 
 
<a href="http://example.com/onepage.html">One Page</a> 
 
<a href="onepage">One Page</a> 
 
<a href="onepage.html">One Page</a>

相关问题