简体   繁体   中英

How can i use generated HTML (using JS) with another JS script?

i am really new to JS, and i am making an excersise that is creating a dynamic menu, it is pretty simple, actually is this exact menu:

http://thecodeplayer.com/walkthrough/vertical-accordion-menu-using-jquery-css3

thing is, if i use this exact code everything works just fine, but if i take out the <div id="accordian"> part and replace it with a JS that generates it (to generate dynamic menus in the future) it stops working, everything shows (even the sub-menus) but can't slide them back up. I have never done anything like this before, do you have any suggestion?

jsBin demo

(please don't use "accordi A n"... it's simply uff nghhh :)
So the accordiOn in the demo uses the ID accordion like in

<div id="accordion">

Simply don't use ID! - Use classes!

<div class="accordion"><!-- menu here bla bla --></div>

and than in jQuery:

/*jQuery time*/
$(document).ready(function(){

    // $(".accordion h3").click(function(){ NO! use dynamic click delegation
    $(document).on("click", ".accordion h3", function(){
        //slide up all the link lists
        // $("#accordian ul ul").slideUp(); Wrong. Reference to this!
        $(this).closest(".accordion").find("ul ul").slideUp();
        //slide down the link list below the h3 clicked - only if its closed
        if(!$(this).next().is(":visible")) {
            $(this).next().slideDown();
        }
    });

});

The above code will work also for dynamically generated accordions cause we used the .on() method that will delegate the click event to existing, but also to future elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM