why does click without body not work

吃可爱长大的小学妹 提交于 2019-12-23 03:05:21

问题


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

if I do this

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

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??


回答1:


A brief explanation can be

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.

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




回答2:


The first method iterates through elements present at the time the handler is executed, so anything that is found at the time is bound.

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

What this allows for is elements created after this point to be treated separately.

Using event delegation (the second method you listed) you can manage all elements that are present in the DOM with the required selector.

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

If you expect to have dynamic elements added to the page a solution using event delegation will allow you to handle all elements regardless of when they were created.




回答3:


try this code:

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

Live is for delegate events to elements even this elements still not exist in the dom



来源:https://stackoverflow.com/questions/18708874/why-does-click-without-body-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!