jQuery toggle children of div

前端 未结 5 1367
别那么骄傲
别那么骄傲 2020-12-06 13:11

I have the following HTML code:

Menu
submenu1
5条回答
  •  一生所求
    2020-12-06 13:31

    $('.dim').on('click', function () {
        //$(this).children('.hidden').toggleClass('.hidden');//as-per AndreasAL's suggestion
        $(this).children('.hidden').toggle();
    });
    
    $('.hidden').on('click', function (event) {
        event.stopPropagation();
    });
    

    Here is a demo: http://jsfiddle.net/76uTr/

    This shows/hides the .hidden elements when clicking on a .dim element but it also allows you to click on a .hidden element and not toggle it's visibility.

    Notice that I used .children() instead of .find() which will only select direct descendants of the root element (.dim).

    Also note that .on() is new in jQuery 1.7 and in this case is the same as .bind().

    UPDATE

    Using event.stopPropagation() we can allow ourselves to nest elements and not let events bubble-up and trigger multiple event handlers:

    $('.dim').on('click', function (event) {
        event.stopPropagation();
        $(this).children('.hidden').toggle();
    });
    
    $('.parent').on('click', function () {
        $(this).children('.dim').toggle();
    });
    
    $('.hidden').on('click', function (event) {
        event.stopPropagation();
    });
    

    Here is a demo: http://jsfiddle.net/76uTr/1/

    Here the .parent element is assumed to be the direct parent of the .dim elements.

提交回复
热议问题