问题
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