preventDefault() won't work for me

笑着哭i 提交于 2019-12-20 04:15:38

问题


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();
});

回答1:


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();
    });



回答2:


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.



来源:https://stackoverflow.com/questions/12162217/preventdefault-wont-work-for-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!