Sorry for the confusing title.. basically I was wondering if this was correct behaviour:
If I have some images each wrapped around in an anchor link and I do
- $(document).on('click', $('a').children('img') , function() {
- // code
- });
example:
http://jsfiddle.net/eawEV/Clicking any image inside 'document' will trigger the event regardless of the selector filtering only images that have anchors as parents?
As opposed to using a string for the selector
- $(document).on('click', 'a > img' , function() {
- // code
- });
example:
http://jsfiddle.net/EU6sX/which filters the selector properly and only triggers the event when images that are descendents of anchors are clicked.
Of course in this situation specifying the selector as a string would make more sense, but I was wondering why object selectors don't get filtered out. I may be misinformed but I thought you could use objects interchangeably with strings for jQuery selectors. This becomes an unsolvable problem if I need to use a more complex jQuery chain as the selector.
If I attach the handler directly, $('a').children('img').on('click', ... it works, obviously, but for dynamically loaded elements I have to use delegated events and this is where I run into the problem. Also, there's no way to convert the object/chain into a string for use as a selector since .selector is deprecated.
I'm thinking this has something to do with event bubbling.. but I could be wrong.
tested with jQuery v1.7.2
Thanks.