我想preventDefault
在父元素上使用,但我不希望它影响子元素。这可以做到吗?
我设置了一个 JsFiddle 来帮助说明我的意思:http: //jsfiddle.net/StephenMeehan/FdwST/5/
我一直在为这个问题挠头几个小时,无法弄清楚......
HTML:
<ul id="SidebarNav">
<li><a href="#">Toys & Games</a></li>
<li><a href="#">Audio Visual</a></li>
<li><a href="#">Electrical</a></li>
<li><a href="#">Photography</a></li>
<li><a href="http://www.google.com">Furniture (Hover over this)</a>
<ul>
<li><a href="http://www.bbc.co.uk">Menu item 1</a></li>
<li><a href="#">Menu item 2</a></li>
<li><a href="#">Menu item 3</a></li>
<li><a href="#">Menu item 4</a></li>
<li><a href="#">Menu item 5</a></li>
</ul>
</li>
<li><a href="#">Music</a></li>
<li><a href="#">Gadgets</a></li>
<li><a href="#">Laptops</a></li>
<li><a href="http://www.google.com">Furniture (Hover over this)</a>
<ul>
<li><a href="http://www.bbc.co.uk">Menu item 1</a></li>
<li><a href="#">Menu item 2</a></li>
<li><a href="#">Menu item 3</a></li>
<li><a href="#">Menu item 4</a></li>
<li><a href="#">Menu item 5</a></li>
</ul>
JavaScript:
// This is my first attempt at writing something useful in jQuery.
$(document).ready(function() {
$("#SidebarNav ul").hide();
$("li:has(ul)").addClass("SubMenu");
// preventDefault removes default events on #SidebarNav a and it's children.
//Is there a way to only target list items with a class of .SubMenu?
// I want to use preventDefault only on .SubMenu a, and still be able to use the links in the drop down menu.
$(".SubMenu a").click(function(e) {
e.preventDefault();
});
// This works, but it sometimes gets confused if there's more than one drop down and the mouse is moved around too fast. Is there a way to force collapse all other SubMenu items on rollover?
$(".SubMenu").on("hover", function() {
$(this).children("ul").delay(100).slideToggle("fast").stop();
});
});