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

I want to use the 'On' function to attach a event because the others are deprecied(live, delegate,click...).

But the problem is : if we generate objects, we need to use a selector in 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 How I do if I want use 'find' method in order to avoid that

    // ?? (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 you !

Upvotes: 3

Views: 1111

Answers (2)

Matt
Matt

Reputation: 75307

The working equivalent to:

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

is...

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

If you to target div's inside the nested list, then you might be able to get away with:

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

... but it depends if you have other ul's in your tbody; you only need to be specific enough in your selector to remove the other elements from consideration. Very rarely would you need to be as specific as tr > ul > li > ul > li > div, and in that case it'd be best to apply a class to an element nearer the div (or the div itself) and select around that instead.

Also note that it is only live() that is depreciated. At the time of writing (1.7.2) delegate() is not, although I believe it will be in 1.8.

There is no talk of depreciating click() or it's shortcut counterparts.

Upvotes: 3

Šime Vidas
Šime Vidas

Reputation: 185883

If you want to select DIV elements which are inside nested lists, then this would be one way to do it:

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

However, I recommend classes. Just set a class on your DIV elements and then:

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

Upvotes: 1

Related Questions