Преобразование относительных путей в абсолютный с помощью 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="#" onclick="location.href='http://site.com/'; return false;">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
});
Как преобразовать относительный путь (var url
) в absolute с помощью jQuery?
Script ничего не должен делать, если это уже абсолютный путь.
Спасибо.
Ответы
Ответ 1
Я уверен, что если вы используете свойство 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, поэтому используйте альтернативный на():
$("a").on('click', function(){
var url = this.href; // use the property instead of attribute
//do something
});
Ответ 2
Не то, что запросил ОП, но если кто-то пытается это сделать для тегов <img>
(как я был, когда нашел этот вопрос), секрет, что он не должен использовать метод jQuery attr.
Это дает вам прямое содержимое атрибута src (которое, если оно относительное, будет относительным):
$('#your_img').attr('src')
В то время как вызов .src на самом объекте DOM всегда дает вам абсолютный путь (что мне нужно):
$('#your_img').get(0).src
Ответ 3
вы можете использовать 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/