简体   繁体   中英

Why is that JQuery live() works while delegate() not working?

The code I'm dealing with is too complicated so I can't paste my codes here.

But the situation I met is taht: A .js file being included in two different htmls,
In one html the delegate() worked but in the other just no effect.
Then I replace delegate() with live() , and then in both html it worked fine.

I'm just curious why this happend..
May it because I included too many different js files in the two htmls and may be causing some conflict?

You have to rember that when you delegate() to some element that element must be present in the dom when you call delegate.

So if you call

 $('#mycontainer').delegate(....

the element with id mycontainer must be present otherwise delegate() won't work. One workaround that cause some overhead is delegating to the document or to the body :

 $('body').delegate()

Live() always works because in reality you are delegating to the body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM