开发者

jQuery toggle menu click through problems

I'm just trying to create a simple toggle menu with jQuery but can't quite get it working.

In it's current state it doesn't slide toggle

HTML:

<ul id="menu">
    <li><a href="one.html">One</a>
        <ul>
            <li><a href="one-one.html">one one</a></li>
            <li><a href="one-two.html">one two</a></li>
            <li><a href="one-three.html">one three</a></li>
        </ul>
    </li>
    <li><a href="two.html">Two</a></li>
    <li><a href="three.html">Three&l开发者_运维技巧t;/a>
        <ul>
            <li><a href="three-one.html">three one</a></li>
            <li><a href="three-two.html">three two</a></li>
            <li><a href="three-three.html">three three</a></li>
        </ul>
    </li>
    <li><a href="four.html">Four</a></li>
</ul>

JS:

$(document).ready(function() {

    // Hide the sub menu items first
    $("ul#menu > li > ul").hide();

    // On click
    $('ul#menu > li').click(function() {

        // If there are sub items toggle them & prevent default click action
        if ( ('ul#menu > li').has('ul').length > 0 ) {
            $('ul#menu > li > ul').slideToggle("slow");
            return false;
        };

    });
});

I need it to slide toggle but also handle the clicks appropriately so the parent list items don't click through but the sub menu items do click through to their relevant pages.


This will do what you want if I understand your question correctly:

$(document).ready(function() {

    // Hide the sub menu items first
    $("ul#menu > li > ul").hide();

    // On click
    $('ul#menu > li > a').click(function() {
        if($('ul', $(this).parent()).children().length) {
            $('ul', $(this).parent()).slideToggle("slow"); 
            return false; 
        } else {
            return true;
        }
    });
    $('ul#menu > li').click(function(e) {
        // If there are sub items toggle them & prevent default click action
        if ($(e.target).is("li")) { 
            // or (e.target == this) if you don't want child li's to toggle
            $('ul', this).slideToggle("slow");
            return false;
        } else {
            return true;
        }

    });
});

You can test it here: http://jsfiddle.net/5fNbh/

Update: takes care of additional cases you specified in comments.


The

return false; 

adds e.preventDefault() (and stop propagation) to the <li> instead of the <a> tag. rebind the click to the <a> or do

$('#menu')
  .find('li').has('ul')
  .find('a').click(function() { return false; });

(see the <a> is now getting the return false?)


This has been done a number of times. Check these links out:

  • http://www.zlwo.com/plugins/15-best-multi-level-menu-jquery-plugins-and-tutorials/
  • http://www.1stwebdesigner.com/freebies/38-jquery-and-css-drop-down-multi-level-menu-solutions/
  • http://www.narga.net/sexy-jquery-drop-down-multi-level-menu/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜