简体   繁体   中英

How to bind an event within dynamically loaded content on a click event?

I have a div inside my html with the id pageContent . When users click various buttons, it will load the appropriate content. When a user clicks the javaQuestions button it loads, javaQuestions.html into the div just fine. However, inside, the javaQuestions.html , I have a collapsible list, and I can't figure out a way to "bind" the li collapse/uncollapse without having the user to click TWICE. Right now what I have is:

$("#pageContent").on('click', 'li', function (){
    $('.collapsible').collapsible();
});

So I guess what happens is, first the user clicks on the button, and it loads content. Then, the user clicks on any li, and it enables the "collapsible()" function, but does not uncollapse/collapse the content. Only when the user clicks a second time does it works fine. I tried adding the line $('.collapsible').collapsible(); into the event that loads the javaQuestions.html content, but it doesn't do anything. Kind of at a roadblock, any ideas?

EDIT: Here is the code that loads the content:

$("#pageContent").on('click', '#javaQuestions', function (e) {
    fadeIn("#pageContent", "../java-questions/javaQuestions.html", 50);
    fadeIn("#commentsContent", "../comments/comment-section.html", 500);
});

I also really want to know how this will function once I figure it out. But as you can see, the above function loads the javaquestions.html, and I can't seem to find a way to ALSO bind 'li' to be collapsible in one swoop.

Have you tried using jQuery bind method? You can bind your handler to, say, body and then you don't have to care about loading and attaching a handler after it.

Update: may be this will help:

$(document).ready(function() {
    $("body").on('click', '#pageContent li', function (){
        $('.collapsible').collapsible();
    });
});

Use this DOCUMENT because it is dynamically loaded

$(document).on("click","li #pageContent",function(){ 
$('.collapsible').collapsible();
});

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