1

我一直在寻找并寻找这个问题的答案。因此,当解决方案非常简单时,我提前道歉。

我想获取当前页面的网址,例如。www.example.com/example.html 并使用 javascript 将其放入链接(以及其他用途)中。

所以它看起来像这样:

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

我已经尝试了很多我知道我需要使用 location.href 但似乎无法让它工作的东西。

这是我最接近它的工作,:

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

谢谢,再次抱歉。我是 JS 和 html 的新手。

Ĵ

4

6 回答 6

1

使用 ID 命名您的元素,例如:<a id="pageLink"></a>然后当文档加载时,您可以运行此代码段:

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

或者,使用 jQuery 之类的东西:

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

编辑针对您在评论中的问题:

我不确定我是否完全理解你,但如果它是固定的,那么你只需在设置它之前连接到 href,例如

$("#pageLink").attr("href", staticUrl + window.location.href);
于 2012-07-01T16:08:13.270 回答
0

可以document.location.href用来查找当前页面的地址

<a id="cool-link">click it!</a>
<script>
jQuery('#cool-link').attr('href', document.location.href)
</script>
于 2012-07-01T16:00:47.097 回答
0

我认为你必须使用window.location.href. 我不是 JS 专家,所以让我知道它是否有效。

于 2012-07-01T16:03:52.050 回答
0

你可以试试这个:

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

您可以将 href 保留为空,只使用 onclick 事件。

希望这可以帮助。

于 2012-07-01T16:08:29.740 回答
0

您可以this在 href 中使用(它是全局对象),但可以在 onclick 中使用。

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

它清除了 onclick,因此您只获得一次,因此如果再次单击它,您可以点击该链接。

于 2012-07-01T16:12:54.133 回答
0
<script>
function gotolink(){
    location.href = location.href;
}
</script>

<a href"#" onclick="gotolink();">Click here!</a>
于 2012-07-01T16:30:39.800 回答