Prevent a link to reload page

前端 未结 7 1667
时光取名叫无心
时光取名叫无心 2020-12-10 16:43

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(functi         


        
7条回答
  •  悲&欢浪女
    2020-12-10 17:04

    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:

    • MDN: event.preventDefault()
    • jQuery: Selectors

    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

提交回复
热议问题