阻止链接重新加载页面 [英] Prevent a link to reload page
问题描述
我正在创建一个响应式菜单: Codepen Demo
I am creating a responsive menu: Codepen Demo
为了避免在点击我的链接时重新加载页面:
To avoid the page to be reloaded when I click a link I have:
$('nav.menu a[href="#"]').click(function () {
$(this).preventDefault();
});
但这似乎不起作用。当我点击一个按钮时,菜单消失。
But this does not seem to work. When I click a button the menu disappears.
有谁知道我做错了什么?
Does anyone knows what I am be doing wrong?
推荐答案
这不是需要 .preventDefault()
的元素,它的点击事件
。
It's not the element that need a .preventDefault()
, its the click event
.
试试这个:
$('nav.menu a').click(function (event) {
event.preventDefault();
// or use return false;
});
我不建议使用 href
作为选择器,最好给它一个 id
或 name
。
I don't recommend to use the href
as selector though, better to give it an id
or name
.
来自MDN,关于.preventDefault():
取消事件,如果它可以取消,不停止进一步传播事件。
From MDN, about .preventDefault():
Cancels the event if it is cancelable, without stopping further propagation of the event.
您可以在这里阅读更多内容:
You can read more here:
- MDN: event.preventDefault()
- jQuery:选择器
- MDN: event.preventDefault()
- jQuery: Selectors
因此,在CSS 指针事件中使用:无;
所有点击都将被忽略。这是一个最近的选择,并在IE11 +,Firefox 3.6 +,Chrome 2.0 +,Safari 4 +中支持。
So by using in the CSS pointer-events: none;
all click will be ignored. This is a "recent" alternative and suported in IE11+, Firefox 3.6+, Chrome 2.0+, Safari 4+.
这篇关于阻止链接重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!