[英]Converting relative paths to absolute with JavaScript
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存在問題。
如果需要支持它,可能需要從this.host
和this.pathname
等不同部分構建href
。 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
});
不是OP問的,但是如果有人試圖為<img>
標簽做這個(就像我在發現這個問題的時候那樣),那就是不使用jQuery的attr方法的秘訣。
這為您提供了src屬性的直接內容(如果它是相對的,則是相對的):
$('#your_img').attr('src')
而在DOM對象上調用.src本身總是給你絕對路徑(我需要的):
$('#your_img').get(0).src
你可以使用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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.