简体   繁体   中英

preventDefault() won't work for me

Why will this refuse to work?
HTML stuff

<div id="nav-bar">  
  <ul>  
    <li>  
      <span>  
        <a href="contact.html">Contact</a>  
      </span>  
    </li>  
  </ul>  
</div>

Javascript stuff

$('div#nav-bar').filter('a').click(function(event){
    event.preventDefault();
});

Filter only filters what is already selected. In your case, the #nav-bar element.

You need this:

$('div#nav-bar a').click(function(event){
        event.preventDefault();
    });

filter is the wrong method to use here. you should either use find to look for elements in a selection:

$('div#nav-bar').find('a')...

or simply combine that into one selector:

$('div#nav-bar a')...

after you've fixed that, your preventDefault will actually get applied and work, theres nothing wrong with that piece of code directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM