Search code examples
jqueryjquery-on

jQuery: .live() and .on() - live returns this as JS object, on return this as jQuery object?


I want to replace an old .live() function with .on().

.live()

 var jqRow = $('#' + id + ' tr');
 jqRow.live("click", function () {
            myFunction(this);
            return false;
        });

.on()

var jqRow = $('#' + id + ' tr');
$(document).on("click", jqRow, function () {
                    myFunction(this);
                    return false;
        });

The this of the .live() method returns a JS object (I need this). The this of the .on() method returns a jQuery object, that causes myFunction to fail.

How can I get the same non jQuery this object like in the live function?


Solution

  • Your syntax is incorrect, your jqRow variable is a jQuery object, but the .on() function only takes string selectors. If you pass a jQuery object, that argument is ignored, and it's the same as setting up a non-delegated event handler on the document itself.

    Change this:

    var jqRow = $('#' + id + ' tr'); // this line creates a jQuery object
    $(document).on("click", jqRow, function () {
        myFunction(this);
        return false;
    });
    

    to this:

    var jqRow = '#' + id + ' tr'; // this line initialises a string
    $(document).on("click", jqRow, function () {
        myFunction(this);
        return false;
    });