[英]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.