I can’t figure out why option (1) doesn’t work.
I have read the live and on but missed/couldn’t find an answer.
Can someone please explain this or point me to the documentation regarding this?
1. $('#MAIN a[href="#PAGE"]').on( 'click',function(event){ alert("1"); });
2. $(document).on('click', '#MAIN a[href="#PAGE"]', function(event){ alert("2"); });
thanks.
The first form hooks up regular events on the links, while the second form hooks up a delegate event on the document level.
The first one is the same as:
The first form needs the links to be present when you run the code. The events won’t be there for links that you add later on.
The second form catches the event when it bubbles up to the document level, so it also works for links that you add later on.
Preferably you should hook up the delegate event as close to the target elements as possible. If the
#MAINelement is present when you hook it up, you would use that instead of the document: