使用JavaScript将相对路径转换为absolute

前端之家收集整理的这篇文章主要介绍了使用JavaScript将相对路径转换为absolute前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
HTML
<a href="/">1</a> // link to http://site.com
<a href="/section/page/">2/a> // link to http://site.com/section/page/
<a href="http://site.com/">3</a>
<a href="../gallery/1/">4</a> // link to http://site.com/gallery/1/

JS:

$("a").live('click',function(){
    var url = $(this).attr("href");
    //do something
});

如何通过jQuery将相对路径(var url)转换为绝对?

如果脚本已经是一个绝对的路径,那么脚本什么也不做.

谢谢.

解决方法

我很确定,如果您使用href属性而不是获取属性,则您将拥有一个完整的域名URL:
$("a").live('click',function(){
    var url = this.href;    // use the property instead of attribute
    //do something
});

正如@Phrogz链接的问题所指出的,听起来好像IE6有问题.

如果需要支持它,您可能需要从不同的部分构建href,如this.host和this.pathname.这些属性由IE6支持.还有其他人可以使用,但您需要验证支持.

jquery live()功能在版本1.7中弃用,并从1.9中删除,因此使用alternate on()

$("a").on('click',function(){
    var url = this.href;    // use the property instead of attribute
    //do something
});
原文链接:https://www.f2er.com/js/154814.html

猜你在找的JavaScript相关文章