使用 Javascript 获取页面的 url 并在链接中使用它 [英] Use Javascript to get url of the page and use it in a link
问题描述
我已经寻找并寻找了这个问题的答案.所以当解决方案很简单时,我提前道歉.
I have looked and looked for an answer to this question. So I apologize in advance when the solution is very easy.
我想获取当前页面的网址,例如.www.example.com/example.html 并使用 javascript 将其放入链接(以及其他用途)中.
I want to take the url of the current page eg. www.example.com/example.html and put this in a link (among other uses) using javascript.
所以它看起来像这样:
<a href"www.example.com/example.html"></a>
我已经尝试了很多我知道我需要使用 location.href 但似乎无法让它工作的东西.
I've tried lots of things I know I need to use location.href but just can't seem to get it to work.
这是我最接近让它工作的方法:
This is the closest I got to getting it to work,:
<a href"javascript:write.location.href;"></a>
谢谢,再次抱歉.我是 JS 和 html 的新手.
Thanks, sorry again. I'm new to JS and html.
J
推荐答案
使用 ID 命名您的元素,例如:<a id="pageLink"></a>
然后当文档加载时,您可以运行此代码段:
Name your element with an ID, like: <a id="pageLink"></a>
and then when the document loads you can run this snippet:
var link = document.getElementById("pageLink");
link.setAttribute("href", window.location.href);
或者,使用 jQuery 之类的东西:
Or, with something like jQuery:
$("#pageLink").attr("href", window.location.href);
编辑在评论中回答您的问题:
EDIT In response to your question in the comments:
我不确定我是否完全理解你,但如果它是固定的,那么你只需在设置之前连接到 href,例如
I'm not sure I'm understanding you completely but if it's fixed, then you'd simply concatenate to the href before setting it, e.g.
$("#pageLink").attr("href", staticUrl + window.location.href);
这篇关于使用 Javascript 获取页面的 url 并在链接中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!