如何将当前url写入href属性?

时间:2016-02-14 18:32:19

标签: jquery

我发现了如何将当前url写入元素:

  <p id="example"></p>

    <script>
    document.getElementById("example").innerHTML = 
    window.location.href;
    </script>

我的结果是:

http://www.animalfriends.de/shop/

现在困难的部分是,我有这个链接:

<a href="#top">Go to top</a>

我希望在href之前将当前页面网址添加到#top并删除最后一个/,以便结果看起来像这样:

<a id="gototop" href="http://www.animalfriends.de/shop#top">Go to top</a>

我试过这样的事,但我输了:

$(#gototop).attr('href', 'window.location.href;');

也许这是不可能的?

1 个答案:

答案 0 :(得分:3)

使用jQuery:

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

使用JavaScript:

document.getElementById("gototop").href = window.location.href;

如果您想将#top添加到网址,只需将window.location.href更改为window.location.href + "#top"

为什么您的代码无效? 因此,下面的代码对您不起作用有两个原因。

$(#gototop).attr('href', 'window.location.href;');
  1. $()接受的参数应该是一个字符串(或包含字符串的变量)。您没有声明#gototop变量。 (在旁注中,不可能声明一个名称以#开头的变量)你也没有说它是一个字符串(你需要用单引号或双引号括起来,比如{{ 1}}或"#gototop"
  2. '#gototop'window.location.href全局变量中的属性(包含字符串)。因此,您应该在没有单引号或双引号的情况下传递它,因为否则您将其作为字符串而不是变量传递。
相关问题