我想在父元素上使用preventDefault
,但我不希望它影響子元素。這可以做到嗎?如何控制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();
});
});
輝煌!謝謝! – StephenMeehan
剛試過這個 - 它的工作原理是,如果只有一個.SubMenu實例,不幸的是它不工作,如果有多個實例。有任何想法嗎? – StephenMeehan
經過更多的頭抓撓我能夠得到這個工作 – StephenMeehan