简体   繁体   English

使用Javascript获取页面的网址并在链接中使用它

[英]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. 因此,当解决方案非常简单时,我会先道歉。

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. www.example.com/example.html,并使用javascript将其放置在链接中(除其他用途外)。

so it would look like this: 所以看起来像这样:

<a href"www.example.com/example.html"></a>

I've tried lots of things I know I need to use location.href but just can't seem to get it to work. 我已经尝试了很多我知道需要使用location.href的东西,但似乎无法使其正常工作。

This is the closest I got to getting it to work,: 这是我最接近使其正常工作的地方:

<a href"javascript:write.location.href;"></a>

Thanks, sorry again. 谢谢,再次抱歉。 I'm new to JS and html. 我是JS和html的新手。

J Ĵ

Name your element with an ID, like: <a id="pageLink"></a> and then when the document loads you can run this snippet: 用ID命名您的元素,例如: <a id="pageLink"></a> ,然后在文档加载时可以运行以下代码段:

var link = document.getElementById("pageLink");
link.setAttribute("href", window.location.href);

Or, with something like jQuery: 或者,使用类似jQuery的东西:

$("#pageLink").attr("href", window.location.href);

EDIT In response to your question in the comments: 编辑在评论中回答您的问题:

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, eg 我不确定我是否完全了解您,但是如果它已修复,那么您只需在设置href之前将其串联即可,例如

$("#pageLink").attr("href", staticUrl + window.location.href);

you can use document.location.href to find the address of the current page 您可以使用document.location.href查找当前页面的地址

<a id="cool-link">click it!</a>
<script>
jQuery('#cool-link').attr('href', document.location.href)
</script>

I think you have to use window.location.href . 我认为您必须使用window.location.href I'm no JS expert, so let me know if it worked. 我不是JS专家,所以让我知道它是否有效。

You can give this a try: 您可以尝试一下:

<a href="" onclick="window.location.href=document.URL">same url link</a>

you can keep the href empty and just use the onclick event. 您可以将href保留为空,而仅使用onclick事件。

Hope this helps. 希望这可以帮助。

You can use this in href (it's global object) but you can in onclick. 你可以使用this在HREF(这是全局对象),但你可以在的onclick。

<a onclick="this.setAttribute('href', location);this.setAttribute('onclick', '');">foo</a>

It clear onclick so you get this only once so you can follow the link if you click it again. 它会清除onclick,因此您只能获得一次,因此如果再次单击该链接,则可以单击该链接。

<script>
function gotolink(){
    location.href = location.href;
}
</script>

<a href"#" onclick="gotolink();">Click here!</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM