如果没有生成
HTML,我该如何使用.on()? jQuery页面说
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()?
解决方法
使用.on,如下面的例子.可以假设body标签总是可用的,因此可以安全地将事件处理程序附加到正文,并将事件委托给选择器,在这种情况下.test.
$(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.