为什么没有身体的点击不起作用 [英] why does click without body not work

查看:84
本文介绍了为什么没有身体的点击不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有多个myclass类,并使用ajax附加了更多这些类

I have multiple myclass class on the page and I append some more of those using ajax

如果我这样做

$('.myclass').click(function(){
          alert(1);
});

它适用于所有非ajax附加请求,但不适用于由ajax附加的类. 对于那些行之有效的

it works for all non-ajax appended requests but not for the classes that get appended by ajax. for those this works

$(body).on('click','myclass',function(){
alert(1);
});

我的问题,那是为什么?

my question, why is that??

推荐答案

简短的解释可以是

使用常规事件注册模型时,它将在处理程序注册执行时将处理程序直接注册到dom中存在的目标.因此,以后动态添加的元素将不会获得这些处理程序.

When you use a normal event registration model, it will register the handlers directly to the targeted which are present in the dom at the point of the handler registration execution. So elements which are added later dynamically will not get those handlers.

对此的解决方案是使用事件委托,在此模型中,将处理程序注册到祖先元素,该祖先元素在页面加载有选择器以滤除源元素时将出现.这利用了事件传播-元素中发生的事件会传播到所有祖先元素(几乎没有例外,例如焦点事件).因此,元素中发生的事件会传播到其中一个元素中的祖先元素,然后注册处理程序,然后将事件源元素(event.target)及其祖先与作为第二个参数传递的选择器进行匹配(如果满足),处理程序被执行. http://api.jquery.com/on/#direct-and-delegated-events

The solution to this is to use event delegation, in this model the handler is registered to a ancestor element which will be present when the page is loaded with the a selector to filter out the source element. This makes use of event propagation - events happening in an element is propagated to all the ancestor elements(there are few exceptions like focus event). So an event happening in an element gets propagated to the ancestor element in one of them the handler is registered then the events source element(event.target) and its ancestors is matched against the selector passed as the second parameter, if it is satisfied then the handler is executed. http://api.jquery.com/on/#direct-and-delegated-events

这篇关于为什么没有身体的点击不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆