Following on from my comment, it's not possible for this
to be a jQuery object. This is because the value of this
within a function is set when the function is invoked, and cannot explicitly be set, it's immutable. It is possible for $(this)
to be a jQuery object though, obviously.
EDIT
As @Anthony Grist pointed out, the real issue here is using a jQuery selector in .on()
. If you change it to pass in a string selector, the value of this
is set accordingly. My apologies for the oversight, here's a working JSFiddle.
For what it's worth, if you're delegating to a single selector, I would just call .on()
on that selector:
$("#foo").on("click", function() {});
Otherwise...
If you're unable to pass in the string selector and have to pass in an actual jQuery object, you can work around it using the event object. This code works:
var jqRow = $('#foo');
$(document).on("click", jqRow, function (e) {
myFunction(e.target);
return false;
});
var jqRow2 = $('#bar');
jqRow2.live("click", function () {
myFunction(this);
return false;
});
function myFunction(x) {
console.log(x);
console.log($(x).attr("id"));
}
Working JSFiddle
Remember, with the syntax you're using there for delegating does not bind an event to jqRow
, it binds it to the document
. jQuery doesn't let you pass in a jQuery object as to be delegated to. So the first part of the above code is fairly pointless, you could just do:
var jqRow = $('#foo');
$(document).on("click", function (e) {
if($(e.target).attr("id") === "foo") {
myFunction(e.target);
}
return false;
});
This is why the value of this
within your .on()
is not the object clicked, as you expected as jQuery can't delegate the event to a jQuery object, it needs a selector. So passing in e.target
should fix your issue.