If you have .class element defined inside header.html then you need to use as below:$(document).on('click','.class',function () { $('#id').slideToggle('fast');}); 事件委托应在稍后添加到 DOM 或加载 DOM 的控件上使用. Event delegation should be used on controls which are added to DOM at later part or after DOM gets loaded. 更新 当您将事件直接附加到如下所示的元素上时:When you attach event directly to element like below:$('.element').click(function(){....});或如下:$('.element').on('click',function(){....});这些事件不会附加到动态添加的元素或加载 DOM 之后添加的元素.因此,您需要将 event 附加到以DOM中特定 element 为目标的 document ,如下所示:those event will not get attached to the dynamically added elements or elements which are added after DOM load. So you need to attach event either to document targeting particular element in DOM as below:$(document).on('click','.element',function(){ ...});或指向其在页面加载期间加载的父级.例如:or to its parent which was loaded during page load. For Ex:假设您具有以下结构:<div class="somediv"> <!--Many other children elements here--></div>现在,您可以通过 append 或通过 load 或其他任何可能的方式添加一个事件,结构将如下所示:Now you will add one more event either by append or by load or in any other possible ways and structure will become as below:<div class="somediv"> <!--Many other children elements here--> <button class="element">Click here<button> <!--This is dynamically added element --></div>现在,您可以将事件附加到 .somediv 而不是附加到 document ,因为它是在 DOM 加载期间添加的,并且是新添加的元素将位于此 .somediv 中.and now you can attach event to .somediv instead of attaching to document, since it was added during DOM load and newly added element will be inside this .somediv. 实际上,这将显着提高代码的性能告诉 jquery 从哪里开始动态搜索添加的 .element 和 jquery 可以更快地搜索它,而不是从文档 This will actually improve performance of code as you are explicitly telling jquery from where to start to search for the dynamically added .element and jquery can search it more faster instead of traversing from document因此,您可以将其编写如下:So you can write it as below:$('.somediv').on('click','.element',function(){ //^^^^parent div ^^^dynamically added element //do anything here}); 这篇关于动态生成的html内的jQuery函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 22:07