Javascript - Jquery, bind a dynamic selector using the 'On' method (not the string)

I want to use the 'On' function to join the event, because others will depreciate (live, delegate, click ...).

But the problem is that if we generate objects, we need to use the selector in the parameters, and this parameter is a string !!

Sample: (context: dynamic table)

//Wrong way

$("#dataTable tbody tr").on("click", function(event){
    alert($(this).text());
});

//Good way

$("#dataTable tbody").on("click", "tr", function(event){
    alert($(this).text());
});

Now, as I do, if I want to use the find method to avoid this

    // ?? (find div)
    $("#dataTable tbody").on("click", "tr > ul > li > ul > li > div", function(event){
            alert($(this).text());
        });

   // What I would like to do
    $("#dataTable tbody").on("click", $(this).find("div"), function(event){
            alert($(this).text());
        });

   //and I don't want to do this :
    $("#dataTable tbody").find('div').on("click", function(event){
            alert($(this).text());
        });

Thank!

+3
source share
2 answers

Work equivalent:

// What I would like to do
$("#dataTable tbody").on("click", $(this).find("div"), function(event){
    alert($(this).text());
});

is an...

// What I would like to do
$("#dataTable tbody").on("click", 'div', function(event){
    alert($(this).text());
});

If you are aiming divinside a nested list, you can get away with:

// What I would like to do
$("#dataTable tbody").on("click", 'ul ul div', function(event){
    alert($(this).text());
});

... , ul tbody; , . , tr > ul > li > ul > li > div, div ( div) .

, live(). (1.7.2) delegate() , , 1.8.

click() .

+3

DIV, , :

$( '#foo' ).on( 'click', 'ul ul div', function () { 

. DIV, :

$( '#foo' ).on( 'click', '.bar', function () { 
+1

All Articles