Prevent a link to reload page

前端 未结 7 1609
时光取名叫无心
时光取名叫无心 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:03

    Here is very easy way to do it inside html.

    <a class="font-weight-bold" href="javascript:void(0);"> Click Here </a>
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-10 17:08
    $('nav.menu a[href="#"]').click(function (e) {
       e.preventDefault();
    });
    
    0 讨论(0)
  • 2020-12-10 17:11

    Try this:

    $('.menu a').click(function(e){
       e.preventDefault(); // stop the normal href from reloading the page.
    });
    

    Working codepen example: http://codepen.io/anon/pen/cynEg

    You did not have a reference to the jquery library included. Also the 'enquire' function is now throwing an error but preventDefault is working.

    Edit I have commented out the second function.

    0 讨论(0)
  • 2020-12-10 17:15

    Use like that:

    $('nav.menu a[href="#"]').click(function (event) {
      event.preventDefault();
    });
    
    0 讨论(0)
  • 2020-12-10 17:17

    Just return false.

    $('nav.menu a[href="#"]').click(function () {
      return false
    });
    
    0 讨论(0)
提交回复
热议问题