[英]Current Page URL in a hyperlink
在下面的代碼中,我正在對URL進行硬編碼。
<a class="button_link" href="https://somewebsite.com/submit/?url=http%3A%2F%2Fsomecrazyurl.com" target="_blank" aria-label="Sharei">
相反,我想要這樣的東西:
<a class="button_link" href="https://somewebsite.com/submit/?url=returnpageurl()" target="_blank" aria-label="Sharei">
編輯:我使用的記錄
$(location).attr('href');
但是什么也沒有返回。
是否有跨瀏覽器Javascript返回頁面的當前URL?
要獲取路徑,可以使用:
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
您可以為此使用jQuery的屬性選擇器。
var linksToGoogle = $('a[href="http://google.com"]');
另外,如果您對以某個URL開頭的鏈接感興趣,請使用attribute-starts-with選擇器:
var allLinks = $('a[href^="http://google.com"]');
如果您正在尋找瀏覽器兼容性解決方案,請使用
window.location.href
與此相關 , document.URL
在Firefox中出現問題的地方
<a class="button__link" href="#" target="_blank" aria-label="Sharei" id="current_url">Current URL</a>
這很容易使用,如下所示,沒有任何復雜性,我發現您沒有為href
屬性分配任何值,默認情況下,它在jquery中將其分配回
現在,下面的一種應該適合您的情況,
$("#current_url").attr("href",window.location.href );
使用window.location.href
JavaScript窗口屬性很容易實現。
HTML示例:
<a href="https://somepage.com" id="link1">my link</a>
Java腳本
var a = document.getElementById('link1');
a.href = a.href + '?returnUrl=' + encodeURIComponent(window.location.href);
使用jQuery:
$('#link1').attr('href', $('#link1').attr('href') + '?returnUrl=' + encodeURIComponent(window.location.href));
注意內置函數encodeURIComponent(str)
參考的使用。
encodeURIComponent()函數通過將表示字符的UTF-8編碼的一個,兩個,三個或四個轉義序列替換某些字符的每個實例來編碼統一資源標識符(URI)組件(對於字符而言,將僅是四個轉義序列)由兩個“代理”字符組成)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.