javascript 如何将#hash 单击添加到元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7891370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:39:37  来源:igfitidea点击:

How to add #hash clicking to an element

javascriptjqueryurlhash

提问by markzzz

When I open my page at http://www.mywebsite.com/where I have this jQuery code :

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

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

});

I'd like, clicking on the locSlideButton2element, add an hash (such as #example) to the url, without make any redirect.

我想,单击该locSlideButton2元素,向 url 添加一个哈希(例如 #example),而不进行任何重定向。

How can I do it?

我该怎么做?

回答by Some Guy

Using plain old vanilla JS:

使用普通的旧香草 JS:

window.location.hash='example';

MDN on window.location

window.location 上的 MDN

回答by adeneo

There's two ways, either you use javascript, where you have access to the window.location.hash, or you bind your click event to an <a href="#example">, and prevent default on click, or think it's cool when your page goes up to the top, and the hash should appear in the browser adress bar.

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

回答by Wenceslao Negrete

Reviving this thread, nowadays you can use history API, works the same as above but also avoids automatically scroll to an id, giving you complete control of what you want to do with that hash:

恢复此线程,现在您可以使用history API,其工作方式与上述相同,但也避免自动滚动到 id,让您完全控制要对该哈希执行的操作:

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

MDN on History API

历史 API 上的 MDN

回答by HackerManiac

simply wrap #locSlideButton2' with` like this

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

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

This will do

这会做