简体   繁体   English

如何在点击事件上将事件绑定到动态加载的内容中?

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

I have a div inside my html with the id pageContent . 我的html内有一个div,其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. 当用户单击它加载的javaQuestions按钮时,将javaQuestions.html插入div就可以了。 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. 但是,在javaQuestions.html内部,我有一个可折叠的列表,并且在没有用户单击TWICE的情况下,我想不出一种方法来“绑定” li折叠/展开。 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. 然后,用户单击任意li,它启用“ collapsible()”功能,但不会取消折叠/折叠内容。 Only when the user clicks a second time does it works fine. 只有当用户第二次单击时,它才能正常工作。 I tried adding the line $('.collapsible').collapsible(); 我尝试添加$('.collapsible').collapsible(); into the event that loads the javaQuestions.html content, but it doesn't do anything. 加载javaQuestions.html内容的事件,但它不会执行任何操作。 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. 但是正如您所看到的,上面的函数加载了javaquestions.html,而且我似乎找不到一种方法也可以将'li'绑定为可折叠的。

Have you tried using jQuery bind method? 您是否尝试过使用jQuery bind方法? You can bind your handler to, say, body and then you don't have to care about loading and attaching a handler after it. 您可以将处理程序绑定到例如body ,然后您不必关心在其后加载和附加处理程序。

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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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