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

时间:2011-03-06 14:29:01

标签: javascript jquery html

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)转换为绝对路径?

如果脚本已经是绝对路径,脚本应该什么都不做。

感谢。

3 个答案:

答案 0 :(得分:24)

我很确定如果您使用href 属性而不是获取属性,那么您将拥有一个包含域名的完整网址:< / p>

$("a").live('click', function(){
    var url = this.href;    // use the property instead of attribute
    //do something
});

如@Phrogz链接的问题所述,听起来好像IE6存在问题。

如果您需要支持,可能需要从hrefthis.host等不同部分构建this.pathname。 IE6支持这些属性。您可以使用其他一些,但您需要验证支持。

jquery live()函数在1.7版中已弃用,已从1.9中删除,因此请使用替代on()

$("a").on('click', function(){
    var url = this.href;    // use the property instead of attribute
    //do something
});

答案 1 :(得分:14)

不是OP提出的要求,但如果有人试图为<img>标签执行此操作(就像我在发现此问题时那样),那么使用jQuery的attr的秘密方法

这为您提供了src属性的直接内容(如果它是相对的,则为相对的):

$('#your_img').attr('src')

而在DOM对象上调用.src总是会给你绝对路径(我需要的):

$('#your_img').get(0).src

答案 2 :(得分:0)

你可以使用jquery mobile

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery.mobile.path.makeUrlAbsolute demo</title>
  <link rel="stylesheet" href="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
  <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
  <script src="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
  <style>
  #myResult{
    border: 1px solid;
    border-color: #108040;
    padding: 10px;
    }
  </style>
</head>
<body>

  <div role="main" class="ui-content">
    <p>The absoulte URL used is http://foo.com/a/b/c/test.html</p>
    <input type="button" value="file.html" id="button1" class="myButton" data-inline="true">
    <input type="button" value="../../foo/file.html" id="button2" class="myButton" data-inline="true">
    <input type="button" value="//foo.com/bar/file.html" id="button3" class="myButton" data-inline="true">
    <input type="button" value="?a=1&b=2" id="button4" class="myButton" data-inline="true">
    <input type="button" value="#bar" id="button5" class="myButton" data-inline="true">
    <div id="myResult">The result will be displayed here</div>
  </div>
<script>
$(document).ready(function() {

   $( ".myButton" ).on( "click", function() {

      var absUrl = $.mobile.path.makeUrlAbsolute( $( this ).attr( "value" ), "http://foo.com/a/b/c/test.html" );

    $( "#myResult" ).html( absUrl );
 })
});
</script>

</body>
</html>

参考:https://api.jquerymobile.com/jQuery.mobile.path.makeUrlAbsolute/

相关问题