If new HTML is being injected into the page,select the elements and attach event handlers after the new HTML is placed into the page.
但我不太确定如何做到这一点.有没有办法“重新加载”事件处理程序?
所以如果我有
$(document).ready(function(){ $('.test').on('click',function(){ var id = $(this).attr('id'); console.log("clicked" + id); }); generatePage(); });
其中generatePage()创建了一堆与.test的div,我将如何重新绑定.on()?
解决方法
$(document).ready(function(){ $('body').on('click','.test',function(){ // Make your changes here var id = $(this).attr('id'); console.log("clicked" + id); }); generatePage(); });
或者如果generatePage()也生成html,head和body标签使用document作为选择器.
$(document).ready(function(){ $(document).on('click',function(){ // Make your changes here var id = $(this).attr('id'); console.log("clicked" + id); }); generatePage(); });
根据jquery documentation .on接受以下参数:
.on( events [,selector] [,data],handler(eventObject) )
包括选择器描述如下:
When a selector is provided,the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element,but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e.,innermost to outermost element) and runs the handler for any elements along that path matching the selector.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。