【发布时间】:2011-12-15 00:53:15
【问题描述】:
当我在http://www.mywebsite.com/ 打开我的页面时,我有这个 jQuery 代码:
$('#locSlideButton2').click(function() {
});
我想,点击locSlideButton2 元素,在网址中添加一个哈希(例如#example),而不进行任何重定向。
我该怎么做?
【问题讨论】:
标签: javascript jquery url hash
当我在http://www.mywebsite.com/ 打开我的页面时,我有这个 jQuery 代码:
$('#locSlideButton2').click(function() {
});
我想,点击locSlideButton2 元素,在网址中添加一个哈希(例如#example),而不进行任何重定向。
我该怎么做?
【问题讨论】:
标签: javascript jquery url hash
【讨论】:
有两种方法,要么使用 javascript,在其中可以访问 window.location.hash,要么将点击事件绑定到 <a href="#example">,并防止默认点击,或者认为当你的页面运行时很酷直到顶部,哈希应该出现在浏览器地址栏中。
【讨论】:
像这样简单地包装#locSlideButton2' with`
<a href="#yourhash"><button id="locSlideButton2">Click me.</button></a>
这样就可以了
【讨论】:
<!doctype html><html lang="en"><title>Test</title><a href="#yourhash"><button id="locSlideButton2">Click me.</button></a></html> 你会看到它不是有效的 html。
恢复这个线程,现在你可以使用history API,工作方式与上面相同,但也避免自动滚动到一个 id,让你完全控制你想用那个哈希做什么:
window.history.pushState({}, "Example Title", "#example");
【讨论】: