【问题标题】:How to add #hash clicking to an element如何将#hash点击添加到元素
【发布时间】:2011-12-15 00:53:15
【问题描述】:

当我在http://www.mywebsite.com/ 打开我的页面时,我有这个 jQuery 代码:

$('#locSlideButton2').click(function() {

});

我想,点击locSlideButton2 元素,在网址中添加一个哈希(例如#example),而不进行任何重定向。

我该怎么做?

【问题讨论】:

    标签: javascript jquery url hash


    【解决方案1】:

    使用普通的旧版 JS:

    window.location.hash='example';
    

    MDN on window.location

    【讨论】:

      【解决方案2】:

      有两种方法,要么使用 javascript,在其中可以访问 window.location.hash,要么将点击事件绑定到 <a href="#example">,并防止默认点击,或者认为当你的页面运行时很酷直到顶部,哈希应该出现在浏览器地址栏中。

      【讨论】:

        【解决方案3】:

        像这样简单地包装#locSlideButton2' with`

        <a href="#yourhash"><button id="locSlideButton2">Click me.</button></a>
        

        这样就可以了

        【讨论】:

        • a 元素内的按钮不是有效的 html。见here
        • 好的,只需将这段代码复制/粘贴到W3C HTML validator 并检查它。 &lt;!doctype html&gt;&lt;html lang="en"&gt;&lt;title&gt;Test&lt;/title&gt;&lt;a href="#yourhash"&gt;&lt;button id="locSlideButton2"&gt;Click me.&lt;/button&gt;&lt;/a&gt;&lt;/html&gt; 你会看到它不是有效的 html。
        【解决方案4】:

        恢复这个线程,现在你可以使用history API,工作方式与上面相同,但也避免自动滚动到一个 id,让你完全控制你想用那个哈希做什么:

        window.history.pushState({}, "Example Title", "#example");
        

        MDN on History API

        【讨论】:

          猜你喜欢
          • 2013-06-07
          • 1970-01-01
          • 1970-01-01
          • 2016-10-31
          • 2015-07-30
          • 2020-08-28
          • 1970-01-01
          • 1970-01-01
          • 2017-07-30
          相关资源
          最近更新 更多