Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - Prevent a link to reload page

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not the element that need a .preventDefault(), its the click event.

Try this:

$('nav.menu a').click(function (event) {
  event.preventDefault();
  // or use return false;
});

I don't recommend to use the href as selector though, better to give it an id or name.

From MDN, about .preventDefault():
Cancels the event if it is cancelable, without stopping further propagation of the event.


You can read more here:


There is a CSS way, using pointer-events.

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+.

Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...